skip to Main Content

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.

  1. 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?
  2. How React clear the old ref? Does it has something to do with calling ref callback twice?

2

Answers


  1. 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 now to say that it is using a real useEffect, but the idea behind it is the same.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search