Snippet

useInterval

js

Intervals are pretty darn tricky in React; if you're not careful, you'll wind up with a "stale" interval, one which can't access current values of state or props.

This hook allows us to sidestep that confusion, and it also gives us a superpower: we can modify the delay without having to worry about stopping and starting the interval.

I learned about this hook from Dan in his blog post on the subject, and he does a fantastic job explaining what all this funkiness is and why you need it. He explains it better than I would be able to, so if you're curious how it works, read his blog post all about it!

I did make one significant change to his version: My version of the hook returns the interval ID, in exactly the same way that window.setInterval would. This allows you to cancel the interval imperatively, if you need to. Note that this is an escape hatch: the primary declarative way to cancel the interval is to set the delay equal to null.

useInterval looks quite a bit like setInterval in its usage:

js

Here's an example of a "Stopwatch" component. useInterval lets us track how much time has elapsed since the user has started the stopwatch.

jsx

Edit on CodeSandbox