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'23import { useIsomorphicLayoutEffect } from 'usehooks-ts'45function useTimeout(callback: () => void, delay: number | null) {6 const savedCallback = useRef(callback)78 // Remember the latest callback if it changes.9 useIsomorphicLayoutEffect(() => {10 savedCallback.current = callback11 }, [callback])1213 // 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 return19 }2021 const id = setTimeout(() => savedCallback.current(), delay)2223 return () => clearTimeout(id)24 }, [delay])25}2627export default useTimeout
Usage
1import { useState } from 'react'23import { useTimeout } from 'usehooks-ts'45export default function Component() {6 const [visible, setVisible] = useState(true)78 const hide = () => setVisible(false)910 useTimeout(hide, 5000)1112 return (13 <div>14 <p>15 {visible16 ? "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 »