Menu

gitpiper

useInterval react Code Snippet in 2024

hookseffectintermediate

Last Updated: 17 December 2024

Implements setInterval in a declarative manner.

  • Create a custom hook that takes a callback and a delay.
  • Use the useRef() hook to create a ref for the callback function.
  • Use a useEffect() hook to remember the latest callback whenever it changes.
  • Use a 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'));

react snippet similar to useInterval For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️