DEV Community

Takuya Kikuchi
Takuya Kikuchi

Posted on

useInterval - React hook

This is a series of tying out the custom hooks introduced in the really good article by team about useful React custom hooks.

8 Awesome React Hooks

useInterval

Counts up by 2 at 2.5-second intervals

Discussion (1)

Collapse
takuyakikuchi profile image
Takuya Kikuchi Author • Edited

At first I was wondering why we need to use useRef() in the useInterval hook.

And I found the explanation by Dan Abramov in his blog Making setInterval Declarative with React Hooks — Overreacted

Problems without useRef()

  • We do setInterval(callback1, delay) with callback1 from first render
  • We have callback2 from next render that closes over fresh props and state
  • But we can’t replace an already existing interval without resetting the time!

Solution

We don’t replace the interval at all.
Instead, introduced a mutable savedCallback variable pointing to the latest interval callback.

  • We setInterval(fn, delay) where fn calls savedCallback.
  • Set savedCallback to callback1 after the first render.
  • Set savedCallback to callback2 after the next render.

This mutable savedCallback needs to “persist” across the re-renders.
=> useRef()