React Hooks - Ref is not avaiable inside useEffect
You should use useCallback instead of useRef as suggested in the reactjs docs.
React will call that callback whenever the ref gets attached to a different node.
Replace this:
const elRef = useRef(null);
useEffect(() => {
console.log("ref", elRef.current);
}, [elRef.current]);
with this:
const elRef = useCallback(node => {
if (node !== null) {
console.log("ref", node); // node = elRef.current
}
}, []);
It's a predictable behaviour.
As mentioned @estus
you faced with this because first time when it's called on componentDidMount
you're getting null
(initial value) and get's updated only once on next elRef
changing because, actually, reference still being the same.
If you need to reflect on every user change, you should pass [user]
as second argument to function to make sure useEffect
fired when user is changed.
Here is updated sandbox.
Hope it helped.
useEffect is used as both componentDidMount and componentDidUpdate, at the time of component mount you added a condition:
if (!user) return null;
return <div ref={elRef}>{user.first_name + " " + user.last_name}</div>;
because of the above condition at the time of mount, you don't have the user, so it returns null and div is not mounted in the DOM in which you are adding ref, so inside useEffect you are not getting elRef's current value as it is not rendered.
And on the click of next as the div is mounted in the dom you got the value of elRef.current.