ReactJS – useLayoutEffect hook

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to set up side-effects or HTTP requests in a functional component.

This hook has the similar functioning like that of useEffect hooks but rather than being called out asynchronously, it has a synchronous effect. This hook is used to load the data in the DOM synchronously and also works in the same phase like that of useEffect hook.

Note: Use useLayoutEffect hook only if useEffect hooks don't give the expected output.

Syntax

useLayoutEffect()

Example

In this example, we will build a React application that displays and updates the name synchronously.

App.jsx

import React, { useLayoutEffect, useState } from 'react';

const App = () => {
   const [name, setName] = useState('Rahul');

   useLayoutEffect(() => {
      if (name === 'Rahul') {
         setName('Bansal');
      }
   }, [name]);
   return <div>{name} has email id of rahul@tutorialspoint.com</div>;
};
export default App;

In the above example, useLayoutEffect hook is called synchronously and hence updated the state before the component is being mounted.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 10:51:11
Advertisements