reactjs
/

React Component Lifecycle – Mounting, Updating & Unmounting

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Component Lifecycle – Mounting, Updating & Unmounting

The Component Lifecycle

Every React component goes through a lifecycle of three phases: Mounting (creation), Updating (growth), and Unmounting (deletion). In modern React, we primarily manage these phases using the useEffect hook in functional components.

  1. Mounting Phase (Birth)

This happens when a component is created and inserted into the DOM. In Class components, componentDidMount is used here. In Functional components, it's represented by a useEffect with an empty dependency array.

React JSXRead-only
1
useEffect(() => {
  console.log('Component Mounted');
  // Good for: API calls, subscriptions, timers
}, []);

  1. Updating Phase (Growth)

Updating occurs when a component's state or props change. React re-renders the component to reflect these changes. You can trigger logic specifically when certain values change by adding them to the dependency array.

React JSXRead-only
1
useEffect(() => {
  console.log('Component Updated because [data] changed');
}, [data]); // Runs on mount + whenever 'data' changes

  1. Unmounting Phase (Death)

This is the final phase when a component is removed from the DOM. It is critical for cleanup to prevent memory leaks, such as clearing intervals or unsubscribing from services.

React JSXRead-only
1
useEffect(() => {
  const timer = setInterval(() => console.log('Tick'), 1000);

  // The Cleanup Function (Unmounting logic)
  return () => {
    clearInterval(timer);
    console.log('Component Unmounted & Timer Cleared');
  };
}, []);

Lifecycle Comparison: Class vs. Functional

Lifecycle EventClass MethodFunctional Hook (useEffect)
MountcomponentDidMountuseEffect(() => {}, [])
UpdatecomponentDidUpdateuseEffect(() => {}, [deps])
UnmountcomponentWillUnmountreturn () => { /* cleanup */ }
Should Update?shouldComponentUpdateReact.memo()

Best Practices

  • Avoid side effects in render: Never update state directly in the function body.
  • Always clean up: Cancel API requests or subscriptions in the return function of useEffect.
  • Dependency Array Accuracy: Ensure all variables used inside useEffect are listed in the dependency array.
  • Use multiple Effects: Break up unrelated logic into separate useEffect calls for better readability.

Try it yourself

import React, { useState, useEffect } from 'react';

function LifecycleDemo() {
  const [count, setCount] = useState(0);
  const [showChild, setShowChild] = useState(true);

  return (
    <div style={{ padding: '20px' }}>
      <h2>Lifecycle Demo</h2>
      <button onClick={() => setShowChild(!showChild)}>
        {showChild ? 'Unmount Child' : 'Mount Child'}
      </button>
      <button onClick={() => setCount(c => c + 1)}>Update Parent (Count: {count})</button>
      
      <hr />
      {showChild && <Child count={count} />}
    </div>
  );
}

function Child({ count }) {
  useEffect(() => {
    console.log('👶 Child: I have arrived (Mounted)');

    return () => {
      console.log('💀 Child: Goodbye world (Unmounted)');
    };
  }, []);

  useEffect(() => {
    console.log('🔄 Child: Prop updated to', count);
  }, [count]);

  return (
    <div style={{ background: '#f0f0f0', padding: '10px' }}>
      <h3>I am the Child Component</h3>
      <p>Parent count: {count}</p>
      <p>Check the console to see lifecycle logs!</p>
    </div>
  );
}

export default LifecycleDemo;

Test Your Knowledge

Q1
of 3

Which hook is used to handle lifecycle events in functional components?

A
useState
B
useContext
C
useEffect
D
useReducer
Q2
of 3

How do you run an effect only once on mount?

A
Pass no dependency array
B
Pass an empty dependency array []
C
Pass [null]
D
Use useOnce hook
Q3
of 3

When does the cleanup function in useEffect run?

A
Only when the page reloads
B
Right after the component mounts
C
Before unmounting and before re-running the effect
D
Every second

Frequently Asked Questions

Does useEffect run on every render?

If you don't provide a dependency array, yes. If you provide an empty array [], it runs only once on mount.

What is the 'Cleanup Function'?

It's the function returned by useEffect. It runs before the component unmounts and before the effect re-runs to clean up previous logic.

Can I use async functions directly in useEffect?

No. You must define an async function inside the effect and call it, because useEffect expects a cleanup function or nothing as a return value, not a Promise.

Previous

react use callback

Next

react controlled components

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.