DEV Community

Discussion on: useInterval - React hook

Collapse
 
takuyakikuchi profile image
TK • 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()