I'm trying to understand which lifecycle point CSS styles are starting to apply to DOM element(s).
Run onto a problem where I need to get the element's clientWidth
after all styles are applied. My tests shows that I can not rely on useEffect
hook, because I get inconsistent result.
I test it with a simple <did/>
element, which is should take full parent width (grid container).
const divRef = useRef()
useEffect(() => {
console.log(divRef.current.clientWidth)
})
<div class="parent">
<div ref={divRef} class="child" />
</div>
I expect the width === 280px, but get (lets say) 980px most of the time.
If I put console.log
inside a timeout
everything starts to work as expected. Clearly useEffect
runs before styles are applied.
Can someone clarify for me how I can get reliable result?