Open In App

ReactJS useLayoutEffect Hook

Improve
Improve
Like Article
Like
Save
Share
Report

The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the page loading, we should always use the useEffect hook.

Prerequisites

The useLayoutEffect hook works in the same phase as componentDidMount and componentDidUpdate methods. We should only use useLayoutEffect if useEffect isn’t outputting the expected result.

Syntax:

useLayoutEffect(setup, dependencies)
or
useLayoutEffect(()=> // some code to execute , dependency //e.g. [] if none)

Approach

React useLayoutEffect is called ton it observes any effects in the dependencies mentioned just like useEffect hook. Instead of blocking the loading it simply updates the UI components given in the setup prop.

Steps to create React Application

Step 1: Create a React application using the following command:

npx create-react-app functiondemo

Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:

cd functiondemo

Project Structure:

Project Structure

Example: We are going to build a name changer application that changes the name of the state after some time and useLayoutEffect hook is called as dependencie variable is updated.

Javascript




// Filename - App.js
 
import React, { useLayoutEffect, useState } from "react";
 
const App = () => {
    const [value, setValue] = useState("GFG");
 
    useLayoutEffect(() => {
        console.log(
            "UseLayoutEffect is called with the value of ",
            value
        );
    }, [value]);
    setTimeout(() => {
        setValue("GeeksForGeeks");
    }, 2000);
 
    return (
        <div
            style={{
                textAlign: "center",
                margin: "auto",
            }}
        >
            <h1 style={{ color: "green" }}>{value}</h1> is
            the greatest portal for geeks!
        </div>
    );
};
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Open the browser and visit http://localhost:3000/ on the browser to see the output.

Peek-2023-10-17-11-32



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads