Why is a React Ref callback (as an arrow function or inline function) called multiple times on initial page load? Why is a React Ref callback (as an arrow function or inline function) called multiple times on initial page load? reactjs reactjs

Why is a React Ref callback (as an arrow function or inline function) called multiple times on initial page load?


Why is the ref callback called three times and why does the component render three times on initial load?

Mainly because inside your callback ref, measuredRef(), you're doing a state update via setHeight().

Here's a step-by-step explanation:

  1. Rendering: Initial Render
  2. Setting height node = <h1>Hello, world</h1>: Initial Render, Ref assignment
  3. Rendering.: Component Re-render due to set height

For the last two prints, refer to caveats of callback refs:

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.

  1. Setting height. node = null: null due to height update
  2. Setting height. node = <h1>Hello, world</h1>: now with DOM element

UPDATE (for the last render #6):

  1. The last render was due to #5 where node != null. So setHeight was called.

i.e #4 (node = null) doesn't cause a re-render cause height is only set if node != null.


See the caveat with ref callbacks: https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs

Without useCallback, a new function callback function measuredRef is created on every render.