I have a react component, where I want to store the width of a div in a state. I am using the following code (extracted from my project):
const Test = (): JSX.Element => {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(123);
useEffect(() => {
setTimeout(() => {
const width = ref.current?.clientWidth || 321;
setWidth(() => width);
}, 1000);
setTimeout(() => {
console.error(width);
}, 2000);
}, []);
...
return (
<div ref={ref}>Test</div>
);
}
When running it, in the console I see the value 123
printed (original value of width) and not the actual width or 321
.
I am sure I am doing something silly, but I have been staring at this code for already quite some time. So, I hope someone can help!
(the reason I am using a setTimeout
is that I have read somewhere, that sometimes you don't get the right value if you get ref.current.clientWidth
right away.