I know this has been asked many times and the answer is always that the effect does not run when refs are mutated but that is not the issue because I run the effect every second until I have an html element with height. This is because the element is rendered later and has a height of 0 until user fills our something and clicks a button.
Here is the code I’m using:
const [containerHeight, setContainerHeight] = useState(200);
const [checkCompnent, setCheckComponent] = useState(0);
useEffect(() => {
let clear = setTimeout(() => {
console.log(
'in timeout',
stickyContainerRef.current,
stickyContainerRef.current?.clientHeight,//allways logs 0
stickyContainerRef.current?.id
);
if (
stickyContainerRef.current &&
stickyContainerRef.current.clientHeight
) {
//never happens
console.log('setting height', stickyContainerRef.current.clientHeight);
setContainerHeight(stickyContainerRef.current.clientHeight);
} else {
console.log('retry');
setCheckComponent((c) => c + 1);
}
}, 1000);
return () => {
clearTimeout(clear);
};
}, [checkCompnent]);
<div id="whynotworky" ref={stickyContainerRef}>
The effect runs every second but the element never has a height other than 0 the id is correctly logged as whynotworky and when I open the dev console and run document.getElementById("whynotworky").clientHeight
it’ll give me 2700. It’s almost like React set the ref but then never updates it on later renders. I’m tempted to ditch the broken ref way and just use document.getElementById but I don’t think you’re supposed to do this.
I’m running this in Firefox and React version is 17.0.2