useTimeout()

Very similar to the useInterval hook, this React hook implements the native setTimeout function keeping the same interface.

You can enable the timeout by setting delay as a number or disabling it using null.

When the time finishes, the callback function is called.

The Hook

1import { useEffect, useRef } from 'react'
2
3// See: https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect
4import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'
5
6function useTimeout(callback: () => void, delay: number | null) {
7 const savedCallback = useRef(callback)
8
9 // Remember the latest callback if it changes.
10 useIsomorphicLayoutEffect(() => {
11 savedCallback.current = callback
12 }, [callback])
13
14 // Set up the timeout.
15 useEffect(() => {
16 // Don't schedule if no delay is specified.
17 // Note: 0 is a valid value for delay.
18 if (!delay && delay !== 0) {
19 return
20 }
21
22 const id = setTimeout(() => savedCallback.current(), delay)
23
24 return () => clearTimeout(id)
25 }, [delay])
26}
27
28export default useTimeout

Usage

1import React, { useState } from 'react'
2
3import { useTimeout } from 'usehooks-ts'
4
5export default function Component() {
6 const [visible, setVisible] = useState(true)
7
8 const hide = () => setVisible(false)
9
10 useTimeout(hide, 5000)
11
12 return (
13 <div>
14 <p>
15 {visible
16 ? "I'm visible for 5000ms"
17 : 'You can no longer see this content'}
18 </p>
19 </div>
20 )
21}

Edit on CodeSandbox

See a way to make this page better?
Edit there »