Please refer to this URL in the React DOCS. A version of this code is also available here.
I understand that inside a Functional React Component
, it is preferred to use the useCallback
hook to create a ref callback as shown in the React Docs URL above, but I wanted to understand what would happen if, instead, a simple arrow function
( inline function ) is used as a ref callback.
So, below, I have modified the code from the above URL to not use the useCallback
hook. Instead, I am just using a regular arrow function
as a ref callback. Additionally, I have added two console.log statements. Here is the code which is also available at this URL.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [height, setHeight] = useState(0);
const measuredRef = node => {
console.log("Setting height. node = ", node);
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
};
console.log("Rendering.");
return (
<div className="App">
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
On loading this app, the following are printed (with numbering added):
1. Rendering.
2. Setting height. node = <h1>Hello, world</h1>
3. Rendering.
4. Setting height. node = null
5. Setting height. node = <h1>Hello, world</h1>
6. Rendering.
Why is the ref callback called three times and why does the component render three times on initial load?