React useTimeout hook
Implements setTimeout() in a declarative manner.
- Create a custom hook that takes a
callbackand adelay. - Use the
useRef()hook to create areffor 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(() => {
const tick = () => {
savedCallback.current();
}
if (delay !== null) {
let id = setTimeout(tick, delay);
return () => clearTimeout(id);
}
}, [delay]);
};