HomeSegun Adebayo

useInterval

A react-friendly alternative to window.setInterval

  • #react
  • #hooks
use-interval.ts
function useInterval(callback, delay) {
  const ref = React.useRef(null);
  const savedCallback = React.useRef(callback);

  React.useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  React.useEffect(() => {
    const tick = () => savedCallback.current();
    if (typeof delay === 'number') {
      ref.current = window.setInterval(tick, delay);
      return () => window.clearInterval(ref.current);
    }
  }, [delay]);

  return ref;
}

Tweet this snippet

Edit on github

Segun Adebayo

Passionate UI engineer looking to bridge the gap between design and code

All rights reserved © Segun Adebayo 2024