Use Effect Hook for Life Cycle Methods in React
Human Life Cycle
Think about the human life cycle:
- Birth (born)
- Grow up
- Death (expire)
React Component Life Cycle
Similarly, React components also have a life cycle:
- Mounting → component is created and added to the DOM
- Updating → component is updated (state or props change)
- Unmounting → component is removed from the DOM
Phases of React Component Life Cycle
Here are the 3 phases:
- Mounting
- Updating
- Unmounting
How to Handle Life Cycle with useEffect
We can handle each life cycle phase using the useEffect hook.
Mounting
Runs only once, when the component is added to the DOM.
Updating
Runs every time the state or props in dependency array change.
Example:
This will run every time the count value changes.
Unmounting
Runs when the component is removed from DOM.
Run on Every Life Cycle Event
If you do not pass a dependency array, useEffect will run after every render.
Unmount Example with Toggle Button
When display is true, the Counter component will show.
When display is false, the Counter component will be removed (unmounted).
Counter.jsx
When Counter is removed from DOM, this code will run.