Friday, December 12, 2025
HomeLanguagesReactJS useLayoutEffect Hook

ReactJS useLayoutEffect Hook

The useLayoutEffect works similarly to useEffect but rather working asynchronously like 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 useEffect hook.

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()

Creating 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: It will look like the following.

Project Structure

Example: In this example, we are going to build a name changer application that changes the name of the state when the useLayoutEffect hook is called.

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import React, { useLayoutEffect, useState } from 'react';
 
const App = () => {
    const [value, setValue] = useState('GFG');
 
    useLayoutEffect(() => {
        if (value === 'GFG') {
            // Changing the state
            setValue('GeeksForGeeks');
        }
        console.log('UseLayoutEffect is called with the value of ', value);
    }, [value]);
 
    return <div>{value} is the greatest portal for neveropen!</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: 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32444 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11951 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12026 POSTS0 COMMENTS
Shaida Kate Naidoo
6945 POSTS0 COMMENTS
Ted Musemwa
7198 POSTS0 COMMENTS
Thapelo Manthata
6891 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS