setInterval in a declarative manner.callback and a delay.useRef() hook to create a ref for the callback function.useEffect() hook to remember the latest callback whenever it changes.useEffect() hook dependent on delay to set up the interval and clean up.const useInterval = (callback, delay) => { const savedCallback = React.useRef(); React.useEffect(() => { savedCallback.current = callback; }, [callback]); React.useEffect(() => { const tick = () => { savedCallback.current(); } if (delay !== null) { let id = setInterval(tick, delay); return () => clearInterval(id); } }, [delay]); };
const Timer = props => {
const [seconds, setSeconds] = React.useState(0);
useInterval(() => {
setSeconds(seconds + 1);
}, 1000);
return <p>{seconds}</p>;
};
ReactDOM.render(<Timer />, document.getElementById('root'));Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️