#JavaScript#React#intervals
Sometimes you need an interval in React.
This could be useful for performing some action regularly, or perhaps animating some variable based on a frame count.
Here's an example of an interval utility
- a utility hook wrapper arounduseInterval
andsetInterval
.clearInterval
import { useEffect } from 'react';/*** React utility hook wrapper around setInterval / clearInterval* @param {function()} callback - A function to be executed every delay milliseconds.* @param {number} delay - The time, in milliseconds, the timer should delay in between executions of callback.* @param {Array<*>} [dependencies] - Optional array of callback dependencies.*/export function useInterval(callback, delay, dependencies) {useEffect(() => {const interval = setInterval(callback, delay);return () => clearInterval(interval);// eslint-disable-next-line react-hooks/exhaustive-deps}, [delay, ...(dependencies ?? [])]);}
Here's an example of using
to maintain a frame count:useInterval
const [frame, setFrame] = useState(0);useInterval(() => {setFrame((frame) => frame + 1);console.log(`Frame #${frame}`);},100);
And a contrived example with an external dependency:
useInterval(() => {setFrame((frame) => frame + 1);console.log(`Frame #${frame}`, externalDependency);},100,[externalDependency]);
If you are using eslint-plugin-react-hooks, you'll see that
as it is implemented above violates theuseInterval
rule. You will still be in the clear as long as you are diligent about defining yourexhaustive-deps
, as in the last example.dependencies