I am writing a React hook that allows me to use setInterval
in my components. In order to do so I need to keep the latest version of the callback in a ref so that it can be accessed from the scope of the interval later on.
This is my code so far:
import { useRef, useEffect } from 'react'
export default function useInterval(
callback: () => void,
delay: number | null,
) {
const callbackRef = useRef(callback)
// Remember the latest callback.
useEffect(() => {
callbackRef.current = callback
})
useEffect(() => {
// Don't schedule if no delay is specified.
if (delay === null) {
return
}
const id = setInterval(() => callbackRef.current(), delay)
return () => clearInterval(id)
}, [delay])
}
My question is about the first instance of useEffect
where the latest value is passed to the ref. According the the React documentation this code will execute after my component has rendered.
I can imagine this is useful when you are passing a ref to an element so you can be sure that it has a value after it has rendered. But if my code doesn't care about when the component renders, does it still make sense to keep this in a useEffect
?
Would it make sense that I rewrite the code as follows:
import { useRef, useEffect } from 'react'
export default function useInterval(
callback: () => void,
delay: number | null,
) {
const callbackRef = useRef(callback)
// Remember the latest callback.
callbackRef.current = callback
useEffect(() => {
// Don't schedule if no delay is specified.
if (delay === null) {
return
}
const id = setInterval(() => callbackRef.current(), delay)
return () => clearInterval(id)
}, [delay])
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…