HomeAmir Hossein Shekari (Vanenshi)

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

Amir Hossein Shekari

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

All rights reserved © Amir Hossein Shekari 2024