As the React doc saying:
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
since we need to free the old dom node’s memory after re-render. But there are 2 questions I still can’t figure out.
- Why React must first call the old ref callback with
null
here? Couldn’t it just call the newer ref callback with the new dom node? - How React clear the old ref? Does it has something to do with calling ref callback twice?
2
Answers
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.
Let’s say you pass your ref callback to a DOM node:
Thinking in terms of the effect gives you:
null
because that’s the "cleanup"Again, this is now to say that it is using a real useEffect, but the idea behind it is the same.
When React calls the ref callback, it needs to know whether it is setting a new ref or removing an old one.
By calling the old ref callback with a null argument, React signals to the callback that the reference to the previous element should be cleared.