Use Effect Hook for Life Cycle Methods in React

Human Life Cycle

Think about the human life cycle:

  1. Birth (born)
  2. Grow up
  3. Death (expire)


React Component Life Cycle

Similarly, React components also have a life cycle:

  1. Mounting → component is created and added to the DOM
  2. Updating → component is updated (state or props change)
  3. Unmounting → component is removed from the DOM


Phases of React Component Life Cycle

Here are the 3 phases:

  1. Mounting
  2. Updating
  3. Unmounting


How to Handle Life Cycle with useEffect

We can handle each life cycle phase using the useEffect hook.


Mounting

useEffect(() => {
// this code will run only when component mounts
}, []);

Runs only once, when the component is added to the DOM.


Updating

useEffect(() => {
// this code will run on update
}, [state1 or props]);

Runs every time the state or props in dependency array change.


Example:

useEffect(() => {
console.log("update phase only");
}, [count]);

This will run every time the count value changes.


Unmounting

useEffect(() => {
return () => {
// this code will run on unmount
};
}, []);

Runs when the component is removed from DOM.


Run on Every Life Cycle Event

useEffect(() => {
// this code will run on every life cycle event (mount + update)
});

If you do not pass a dependency array, useEffect will run after every render.


Unmount Example with Toggle Button

const [display, setDisplay] = useState(false);

{display ? <Counter count={count} data={data} /> : null}

<button onClick={() => setDisplay(!display)}>Toggle</button>

When display is true, the Counter component will show.

When display is false, the Counter component will be removed (unmounted).


Counter.jsx

useEffect(() => {
return () => {
console.log("unmounting phase only");
};
}, []);

When Counter is removed from DOM, this code will run.