Life cycle of a react component.

bepo

In this article, we gonna learn about the lifecycle of a React component, do we have any idea about what is called first useEffect or useLayoutEffect? we will know after looking at the flow diagram of a React component.

react-component-flow-diagram

The diagram is created by Donavon

There are 3stages of a component

  1. Mount (when the component is rendered for the first time)
  2. Update (when the component is re-rendered)
  3. Unmount (when the component is removed from the DOM)

Lifecycle

1. Run Lazy initializers (Mount stage)

functions passed to the useState and useReducer hooks are lazy initializers. Those functions are called first and only in the mount stage.

2. Render (Mount and Update stage)

It will run the rest of the code present in our component other than hooks.

3. React updates dom (Mount and Update stage)

React will create (mount stage) or update the virtual dom.

4. run useLayoutEffect's cleanup funtion (unmount stage)

The cleanup method of useLayoutEffect will be called.

5. run useLayoutEffect (Mount and Update stage)

useLayoutEffect will be called.

6. Browser paint screen (Mount and Update stage)

Browser will paint the screen, here the real dom will be updated based on the changes present in the virtual dom.

7. run useEffect's cleanup funtion (unmount stage)

The cleanup method of useEffect will be called.

8. run useEffect (Mount and Update stage)

useEffect will be called.


The lifecycle will continue whenever the component is updated.

Code

import { useEffect, useLayoutEffect, useState } from  "react";
 
const  App  = () => {
 
   const [count, setCount] =  useState(() => {
     console.log("Lazy initializer called");
     return  12;
   });
   
   console.log("render rest of the code"); 
 
   useLayoutEffect(() => {
     // called before updating the real dom
     console.log("layout effect");
	 return () => {
	  console.log("layout cleanup method");
	 };
	}, [count]);
	
   useEffect(() => {
     // after rendering the UI to browser
	 console.log("effect");
	 return () => {
	  console.log("effect cleanup method");
	};
   }, [count]);
 
	return (
	   <>
		 <h1>Hello world</h1>
	     <button  onClick={() =>  setCount(count  =>  count + 1)}>
	       {count}
	     </button>
	   </>
	);
};
 
export  default  App;

Thanks for reading the article 🎉