Sunday, 13 October 2024

React Hooks - useLayoutEffect

v useLayoutEffect Hook

Ø useLayoutEffect is used for measuring dom elements, animating dom elements, fixing flickering  issue, Api calling.

Ø useLayout Effect works similarly to useEffect but it is called before  the user Interface gets mounted.

Ø useEffect gets called after printing the dom elements. useLayoutEffect gets called before printing  the DOM elements

Ø For Example if you change colour of Dom Element using useState hook then it will display first dom element then after change color of dom element that will called blink or flicker issue. But when we change colour using useLayoutEffect then first it will change the colour and after that it will display dom element on the webpage.

 

Example :

Ø In below code useLayoutEffect function is after useEffect function but in console it will display before useEffect function. useLayoutEffect is executed before useEffect. So first useLayoutEffect is executed then display dom element and then after useEffect executed.

Ø useEffect called after mounting dom element and useLayoutEffect called before mounting dom element.

 

import React, { useEffect, useLayoutEffect } from ‘react’;

import ‘../App.css’;

 

function App() {

useEffect(() => {

            console.log(‘Message from useEffect’);

},[])

 

useLayoutEffect(() => {

            console.log(‘Message from useLayoutEffect’);

},[])

 

         return (

                     <>

                                 <h2>Test Message </h2>

                                

 

{

Array(40000).fill(‘’).map((item, index) =>(

   <li key={index}>

            {Math.pow(Math.random(),10)}

  </li>

))

}

</>

);

}

export default App;




No comments:

Post a Comment

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...