Implements setTimeout
in a declarative manner.
- Create a custom hook that takes a
callback
and adelay
. - Use the
useRef()
hook to create aref
for the callback function. - Use the
useEffect()
hook to remember the latest callback. - Use the
useEffect()
hook to set up the timeout and clean up.
const useTimeout = (callback, delay) => { const savedCallback = React.useRef(); React.useEffect(() => { savedCallback.current = callback; }, [callback]); React.useEffect(() => { function tick() { savedCallback.current(); } if (delay !== null) { let id = setTimeout(tick, delay); return () => clearTimeout(id); } }, [delay]); };
Examples
const OneSecondTimer = props => { const [seconds, setSeconds] = React.useState(0); useTimeout(() => { setSeconds(seconds + 1); }, 1000); return <p>{seconds}</p>; }; ReactDOM.render(<OneSecondTimer />, document.getElementById('root'));
Recommended snippets
Implements
fetch
in a declarative manner.Implements
setInterval
in a declarative manner.Returns a stateful value, persisted in
localStorage
, and a function to update it.