Open In App

When should we use useLayoutEffect instead of useEffect?

useLayoutEffect is used when you want to update how the webpage looks right after it’s rendered. This ensures that changes happen immediately before the browser shows anything on the screen. It’s crucial for tasks like measuring element sizes or positioning elements accurately based on their layout.

Why we should use useLayoutEffect instead of useEffect ?:

Example: Below is the example of using useLayoutEffect instead of useEffect.




import React, {
    useState,
    useLayoutEffect
} from 'react';
 
function ExampleComponent() {
    const [width, setWidth] = useState(0);
 
    useLayoutEffect(
        () => {
            // This effect runs before the browser paints changes
            console.log('useLayoutEffect - Component rendered');
            setWidth(
                document.documentElement.clientWidth
            );
            return () => {
                console.log('useLayoutEffect - Cleanup');
            };
        }
    );
 
    return (
        <div>
            <p>
                Window Width: {width}px
            </p>
        </div>
    );
}
 
export default ExampleComponent;

Output:

Output


Article Tags :