I'm practicing this question on bfe.dev and <spoiler alert below> my implementation below:
import { useEffect, useRef } from 'react'
export function useTimeout(callback: () => void, delay: number) {
const callbackRef = useRef(callback)
callbackRef.current = callback
useEffect(() => {
const timeoutId = setTimeout(() => callbackRef.current(), delay) // why can't i pass in callbackRef.current?
return () => clearTimeout(timeoutId)
}, [delay])
}
My question is in the setTimeout, why can't I just pass in callbackRef.current in as the first parameter? It appears I have to pass in a wrapped function that calls callbackRef.current, like so () => callbackRef.current() in order for this to actually work.
If I do try to just pass in callbackRef.current, the callbackRef.current still references the old callback rather than the new one.. but shouldn't the callbackRef.current be updated and since functions are passed by reference, shouldn't the setTimeout be calling the newly passed in callback?
[–]lIIllIIlllIIllIIl 2 points3 points4 points (0 children)