Middle
What is the difference between useEffect and useLayoutEffect? Can you give an example of using useLayoutEffect? What happens if heavy computations are performed inside useLayoutEffect?
sobes.tech AI
Answer from AI
useEffect and useLayoutEffect are similar but differ in the timing of execution:
useEffectis called after the browser has painted the updates on the screen (asynchronously).useLayoutEffectis called synchronously immediately after all DOM mutations but before the browser has painted the updates.
This means that useLayoutEffect blocks the painting, allowing operations that need to happen before rendering (such as measuring the DOM, synchronizing styles).
Example of using useLayoutEffect:
import React, { useLayoutEffect, useRef, useState } from 'react';
function Component() {
const ref = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
// Measure the width of the element before painting
if (ref.current) {
setWidth(ref.current.offsetWidth);
}
}, []);
return <div ref={ref}>Width: {width}px</div>;
}
If heavy computations are performed inside useLayoutEffect, it will block the page rendering, leading to delays and UX degradation (such as flickering or interface lag). Therefore, heavy operations are better performed in useEffect or asynchronously.