Consider following pattern:
const Comp = ({ handler })=> {
// handler is some callback of the form ( ) => void
useSomeHook(handler);
//...
}
function useSomeHook(cb) {
const ref = useRef()
useEffect(() => {
ref.current = cb; // update ref before second useEffect
})
useEffect(() => {
// use the current (most recent) ref value
const iv = setInterval(() => { ref.current() }, 3000)
return () => { clearInterval(iv) };
}, []) // run only after first render
}
Question: Can I rely on the fact, that first useEffect
is always executed before second useEffect
, so ref
has already been updated?
Background: My intent is to avoid memoizing passed-in callback in Comp
(useCallback
) and setting cb
as dep. I am specifically interested, if this mutable ref pattern is valid in React world - above is just a contrived example.
I thought, the answer would be a clear "Yes!", after having read a tweet from Dan Abramov. Though, following issue states:
We do not make guarantees about sibling order, whether within a component or between siblings. This is because strong guarantees there hinder refactoring. Within a component, you should be able to re-order Hooks—especially, custom ones.
Did I have interpreted above statement wrong - or are the links a bit contradictory? Appreciate any clarifications.
PS: I am aware of linked post. This question is more about the general pattern, official docs and related to mentioned contradictory(?) statements.
Thanks!