Open In App

Why useLayoutEffect Hook is beneficial in React ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

useLayoutEffect is a React Hook that is similar to useEffect, but it fires synchronously after all DOM mutations. It’s typically used for imperative DOM mutations or measurements, where you need to be sure that the DOM is updated before continuing. Here’s an example of how you might use useLayoutEffect

Prerequisites:

Steps to Create Application:

Step 1: Initialize a new React project using Create React App.

npx create-react-app uselayouteffect
cd uselayouteffect

Example to implement useLayoutEffect: In this example there is an implementation of useLayoutEffect which handles the changing of background color while clicking anywhere on the screen.

Javascript




// src/App.js
import React from 'react';
import DynamicBackgroundColor from './DynamicBackgroundColor';
 
function App() {
    return (
        <div className="App">
            <DynamicBackgroundColor />
        </div>
    );
}
 
export default App;


Javascript




// src/DynamicBackgroundColor.js
 
import React, { useState, useLayoutEffect } from 'react';
 
const DynamicBackgroundColor = () => {
    const [color, setColor] = useState('white');
 
    useLayoutEffect(() => {
        const updateColor = () => {
            const randomColor =
                    '#' + Math.floor(Math.random() * 16777215).toString(16);
            setColor(randomColor);
        };
 
        updateColor(); // Initial color update
 
        // Add event listener to update color on click
        window.addEventListener('click', updateColor);
 
        // Cleanup function to remove event listener
        return () => {
            window.removeEventListener('click', updateColor);
        };
    }, []);
 
    return (
        <div style={{ backgroundColor: color, minHeight: '100vh', display: 'flex'
        , justifyContent: 'center', alignItems: 'center' }}>
            <h1>Click Anywhere to Change Background Color</h1>
        </div>
    );
};
 
export default DynamicBackgroundColor;


To start the application run the following command.

npm start

Output:

Animation38



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads