What are the differences between useEffect and useLayoutEffect hooks?
sobes.tech AI
Answer from AI
useEffect and useLayoutEffect are React hooks that allow you to perform side effects in functional components, but they differ in timing:
-
useEffectruns after the browser has painted the updates on the screen. It is an asynchronous effect that does not block the rendering. Suitable for data fetching, subscriptions, timers, and other operations that do not affect visual display. -
useLayoutEffectruns synchronously immediately after React has applied all DOM mutations but before the browser has painted them on the screen. This allows performing operations that need to happen before display (e.g., measuring DOM elements, synchronizing scroll) to avoid flickering.
Example:
useLayoutEffect(() => {
// Measure the size of the element and update state immediately
const rect = ref.current.getBoundingClientRect();
setSize({ width: rect.width, height: rect.height });
}, []);
useEffect(() => {
// Load data from server
fetchData().then(setData);
}, []);
Using useEffect for measurements may cause visual shifts, as the effect runs after the render.