Menu

gitpiper

useTimeout react Code Snippet in 2023

hookseffectintermediate

Last Updated: 1 March 2023

Implements setTimeout 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 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]); };
const OneSecondTimer = props => { const [seconds, setSeconds] = React.useState(0); useTimeout(() => { setSeconds(seconds + 1); }, 1000); return <p>{seconds}</p>; }; ReactDOM.render(<OneSecondTimer />, document.getElementById('root'));

react snippet similar to useTimeout For You in February 2023

Subscribe to our Newsletter

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

© 2023 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! ✌️