ReactJS - useLayoutEffect Hook



The new hook ‘useLayoutEffect’ is introduced in the version of React 18. This hook can be passed in the render function of a component to force the react library to consider the page's layout and adjust its calculations for things like spacing and overflow.

In simple terms, It is useful when we need to inspect how different elements of a web page look and then make changes based on what we discover. It operates quickly allowing changes to be made before the web page is visually updated. This contributes to a more fluid and responsive user experience. In terms of when it runs, it's comparable to o componentDidMount and componentDidUpdate methods, except it is for functional components in React rather than class components. It makes certain that modifications are made before the browser displays the updates.

Syntax

useLayoutEffect(setup, deps)

Parameters

  • setup − This is where you place the code that runs when your React component is added to a web page.

  • deps − Dependencies serve as a checklist of the elements on which our setup code is dependent. It can be anything from outside our component like information, data or something we generate within the component.

Return Value

It returns undefined.

How to use it?

The useLayoutEffect hook in React accepts two parameters. The first parameter is an effect function, while the second parameter is an array of dependencies. The first parameter, effect, is usually undefined or returns a cleanup function. The useLayoutEffect function signature is seen in the following code −

import React, { useLayoutEffect } from "react";
const App = props => {
   useLayoutEffect(() => {
      
      //Perform an action and either return undefined or clean up function.
      return () => {
         //Do  clean up here
      };
   }, [dependencies]);
}; 

The useLayoutEffect hook is a powerful React component that allows us to direct where the input focus goes while rendering. This capability can be used to implement a wide range of user interactions, from hiding information to creating a dropdown menu. It allows us to fully customize what occurs behind the scenes with only one line of code.

Examples

Example − Simple User Input App

This app consists of a simple input field. As we type into the input, the entered value is immediately logged. It uses React.useLayoutEffect to capture and display the input value in real-time, providing a dynamic interaction with the user's input.

import React from "react";

function App() {
   const [value, setValue] = React.useState("");   
   React.useLayoutEffect(() => {
      console.log("Input value: ", value);
   }, [value]);
   
   return (
      <div>
         <input
         type="text"
         value={value}
         onChange={(e) => setValue(e.target.value)}
         />
         <p>You typed: {value}</p>
      </div>
   );
}

export default App;

Output

typed hello

Example − Toggle Button App

In this app, we will have a button to toggle between online and offline status. The current online status is logged using React.useLayoutEffect, and a message is displayed accordingly. So the code for this app is as follows −

import React from "react";

function App() {
   const [isOnline, setOnline] = React.useState(true);   
   React.useLayoutEffect(() => {
      console.log("Online status: ", isOnline ? "Online" : "Offline");
   }, [isOnline]);
   
   return (
      <div>
         <h2>{isOnline ? "You are online" : "You are offline"}</h2>
         <button onClick={() => setOnline(!isOnline)}>
            Toggle Online Status
         </button>
      </div>
   );
}

export default App;

Output

online status

Example − Counter App

So let's see a simple counter application with the help of useLayoutEffect that increments the count on a button click and prints the value using the effect hook in the console.

import React from "react";

function App() {
   const [count, setCount] = React.useState(0); // Initialize with a number   
   React.useLayoutEffect(() => {
      console.log(count);
   }, [count]);
   
   return (
      <div>
         <h1>The count is {count} </h1>
         <button onClick={() => setCount(count + 1)}>Click here</button>
      </div>
   );
}

export default App;

Output

count is 6

This code is a React component that tracks the value of the count state whenever it changes with the useLayoutEffect hook. It shows the current count on the web page and allows the user to increase it by clicking a button.

Limitations

  • The useLayoutEffect hook can only be used at the top level of our component or within other custom hooks. It cannot be used within loops or conditions. Create a separate component and place the effect there if we need to use it in a loop or condition.

  • When we use React's Strict Mode in development mode, React performs additional checks to ensure that our cleaning code matches our setup code. If we run into problems as a result of this, make sure our cleaning code properly undoes what our setup code did.

  • If any of the items on which our effect depends are objects or functions produced within our component, the effect can execute more frequently than necessary. To fix this we can remove unnecessary object and function dependencies.

reactjs_reference_api.htm
Advertisements