Create an Interval Hook

To create an interval hook, pass in a function to be called every interval with the args passed in the hook.

jsx
1import { useRef, useEffect, useState } from 'react';
2
3const useInterval = (callback, delay) => {
4 const savedCallback = useRef();
5
6 useEffect(() => {
7 savedCallback.current = callback;
8 }, [callback]);
9
10 useEffect(() => {
11 const tick = () => {
12 savedCallback.current();
13 };
14
15 if (delay !== null) {
16 let id = setInterval(tick, delay);
17 return () => clearInterval(id);
18 }
19 }, [delay]);
20};
21
22// Usage
23const Timer = () => {
24 const [seconds, setSeconds] = useState(0);
25
26 useInterval(() => {
27 setSeconds(seconds + 1);
28 }, 1000);
29
30 return <div>Seconds: {seconds}</div>;
31};