React useInterval hook

React, Hooks, Effect · Nov 16, 2020

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.createRoot(document.getElementById('root')).render(
  <Timer />
);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Write a useInterval hook in React

    Wrapping your mind around React hooks and how they interact with setInterval() can be difficult. Here's a guide to get you started.

    React, Hooks · Sep 28, 2021

  • React useFetch hook

    Implements fetch() in a declarative manner.

    React, Hooks · May 1, 2022

  • React useTimeout hook

    Implements setTimeout() in a declarative manner.

    React, Hooks · Nov 16, 2020