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:
- Rendering: Initial Render
- Setting height
node = <h1>Hello, world</h1>
: Initial Render, Ref assignment - 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.
- Setting height. node = null: null due to height update
- Setting height.
node = <h1>Hello, world</h1>
: now with DOM element
UPDATE (for the last render #6):
- The last render was due to #5 where
node != null
. SosetHeight
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.