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.
- Why must React first call the old ref callback with
null
here? Couldn't it just call the newer ref callback with the new dom node? - How does React clear the old ref? Does it have something to do with calling ref callback twice?