As the React documentation mentions:
If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one.
I can understand that the el is set to null, because we need to free the old dom node's memory after the re-render. But, there are 2 questions I still can't figure out.
null here? Couldn't it just call the newer ref callback with the new dom node?You can think about ref resetting for callback ref as an effect. It's not that way but I think the rewording of the problem does help with understanding.
useEffect(() => {
ref.current = element
return () => {
ref.current = null
}
})
Let's say you pass your ref callback to a DOM node:
<div ref={(element) => console.log(element)} />
Thinking in terms of the effect gives you:
null because that's the "cleanup"Again, this is not to say that it is using a real useEffect, but the idea behind it is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With