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