At first I was wondering why we need to use useRef() in the useInterval hook.
useRef()
useInterval
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!
setInterval(callback1, delay)
callback1
callback2
Solution
We don’t replace the interval at all. Instead, introduced a mutable savedCallback variable pointing to the latest interval callback.
savedCallback
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()
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
At first I was wondering why we need to use
useRef()
in theuseInterval
hook.And I found the explanation by Dan Abramov in his blog Making setInterval Declarative with React Hooks — Overreacted
Problems without
useRef()
Solution
We don’t replace the interval at all.
Instead, introduced a mutable
savedCallback
variable pointing to the latest interval callback.This mutable savedCallback needs to “persist” across the re-renders.
=>
useRef()