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

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