React Component Lifecycle

📘 React.js 👁 28 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

The React component lifecycle describes the different stages a component goes through from creation to removal. Understanding this helps you manage data fetching, side effects, and cleanup effectively.


Lifecycle Phases

React components go through three main phases:

  1. Mounting – Component is created and added to the DOM

  2. Updating – Component re-renders due to state or prop changes

  3. Unmounting – Component is removed from the DOM


Lifecycle in Class Components (Traditional)

Mounting

  • constructor()

  • render()

  • componentDidMount()

componentDidMount() { // API calls, subscriptions }

Updating

  • render()

  • componentDidUpdate(prevProps, prevState)

componentDidUpdate(prevProps) { if (this.props.id !== prevProps.id) { // React to changes } }

Unmounting

  • componentWillUnmount()

componentWillUnmount() { // Cleanup }

Lifecycle in Functional Components (Modern)

Functional components use Hooks instead of lifecycle methods.


useEffect as Lifecycle Replacement

Lifecycle PhaseHook Equivalent
MountinguseEffect(() => {}, [])
UpdatinguseEffect(() => {}, [deps])
UnmountingCleanup function

Mounting Example

useEffect(() => { console.log("Component mounted"); }, []);

Updating Example

useEffect(() => { console.log("Value changed"); }, [value]);

Unmounting Example (Cleanup)

useEffect(() => { const timer = setInterval(() => {}, 1000); return () => clearInterval(timer); }, []);

Complete Lifecycle Example

function Example() { useEffect(() => { console.log("Mounted"); return () => { console.log("Unmounted"); }; }, []); return <div>Lifecycle Demo</div>; }

When Does Re-render Happen?

  • State changes (useState, useReducer)

  • Props change

  • Parent component re-renders


Common Use Cases

  • Fetching data on mount

  • Updating UI when props/state change

  • Cleaning up timers and listeners

  • Managing subscriptions


Best Practices

  • Keep effects focused

  • Clean up side effects

  • Avoid unnecessary re-renders

  • Use dependency arrays correctly


Key Points

  • Lifecycle defines component behavior over time

  • Hooks replace lifecycle methods

  • useEffect handles side effects

  • Cleanup is critical


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes