Senior
When does useLayoutEffect trigger and why is it needed?.
sobes.tech AI
Answer from AI
useLayoutEffect runs synchronously immediately after all DOM mutations but before the browser has a chance to paint updates on the screen. This allows performing operations that should happen before rendering, such as measuring element sizes or synchronizing animations.
The main difference from useEffect is that useEffect runs asynchronously after painting, while useLayoutEffect runs synchronously, blocking the paint until the effect is complete.
Example of usage:
import React, { useLayoutEffect, useRef, useState } from 'react';
function Component() {
const ref = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
if (ref.current) {
setWidth(ref.current.offsetWidth);
}
}, []);
return <div ref={ref}>Width: {width}px</div>;
}
Here, useLayoutEffect ensures that the width measurement occurs before rendering, preventing flickering.