Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does React clear the old ref when calling ref callback after re-render?

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.

  1. 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?
  2. How does React clear the old ref? Does it have something to do with calling ref callback twice?
like image 440
Chor Avatar asked Apr 09 '26 22:04

Chor


1 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.

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:

  1. when the component mounts, it calls the ref callback with that element
  2. when the component unmounts, it calls the ref callback with null because that's the "cleanup"
  3. when the component changes, it first calls the "cleanup" and then it sets up the new "effect".

Again, this is not to say that it is using a real useEffect, but the idea behind it is the same.

like image 148
Jakub Michálek Avatar answered Apr 12 '26 11:04

Jakub Michálek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!