What is the difference between useEffect and useLayoutEffect? When should useLayoutEffect be used?
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 when they are executed.
-
useEffect runs after the browser has painted the updates on the screen. It is asynchronous relative to rendering, so it does not block the UI display. It is typically used for data fetching, subscriptions, or state changes that do not immediately affect the visual display.
-
useLayoutEffect runs synchronously immediately after all DOM mutations but before the browser repaints the screen. This means it blocks the painting until the effect is executed. It is used when you need to measure or modify the DOM (e.g., calculating element sizes, synchronizing scrolls, animations) to avoid flickering or incorrect rendering.
When to use useLayoutEffect:
- When you need to perform operations that affect the visual presentation and must be completed before the user sees the changes.
- For example, adjusting styles, calculating element sizes, synchronizing scrolls.
Example:
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 immediately after DOM changes
setWidth(ref.current.offsetWidth);
});
return <div ref={ref}>Width: {width}px</div>;
}