blogdoodlesgamessounds
blogdoodlesgamessounds
  1. Home
  2. blog
  3. useInterval

useInterval

A general React hook for intervals.

Feb 11, 2021
#JavaScript#React#intervals

Motivation

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

useInterval
- a utility hook wrapper around
setInterval
and
clearInterval
.

Code

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

useInterval
to maintain a frame count:

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]
);

Caveats

If you are using eslint-plugin-react-hooks, you'll see that

useInterval
as it is implemented above violates the
exhaustive-deps
rule. You will still be in the clear as long as you are diligent about defining your
dependencies
, as in the last example.