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

Usage

1import { 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 »