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.
The diagram is created by Donavon
There are 3stages of a component
- Mount (when the component is rendered for the first time)
- Update (when the component is re-rendered)
- 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
Thanks for reading the article 🎉