I have a requirement for React's ref clientHeight to report the height of a component and I have come across this strange behaviour where the same ref reports different values for its clientHeight depending on how it is accessed. If I output text inside a div the ref outputs the correct height consistently.
const test = useRef(null)
useEffect(() => {
console.log(test)
console.log(test.current.clientHeight)
},[])
return <div ref={test}>
<Input value={state.multiLineString} multiline/>
</div>
These images output me accessing clientHeight from the test.current object and directly via test.current.clientHeight. Observe that they reconcile.


These images output me accessing the clientHeight in both the same ways but with the text from state passed to the input which is multiline. Observe that they do not reconcile despite the fact that the first object output has the correct value.


Why is this happening because I am very confused and have exhausted every resource I could find. Thank you.
EDIT
repo here
https://codesandbox.io/s/optimistic-hermann-q6mnv?file=/src/App.js
If you have an area that takes a size later, such as the image area, in the first case, the clientHeight is displayed without calculating that size. In this case, if the container of the image area is given a static height, the correct result will be shown.
In a case such as yours, you probably should use a callback ref paired with something like ResizeObserver. For ease of use, take a look at the use-resize-observer library.
A code excerpt using this library, taken from their docs:
const App = () => {
const {
ref,
width = 1,
height = 1,
} = useResizeObserver();
return (
<div ref={ref}>
Size: {width}x{height}
</div>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With