React Component Life Cycle: Understanding How Components Work Behind the Scenes

Last updated 2 months, 2 weeks ago | 126 views 75     5

Tags:- React

Introduction: Why React Component Lifecycle Matters

Every React component goes through a life cycle—from being created, to updating, and finally being removed. Understanding this life cycle is critical for tasks like:

  • Fetching API data at the right time

  • Managing side effects

  • Cleaning up resources

  • Debugging unexpected renders

Whether you use class components or modern functional components with hooks, knowing the lifecycle phases helps you optimize performance and write cleaner, predictable code.


What Is the React Component Life Cycle?

The React lifecycle describes the sequence of events that happen from the birth of a component to its death.

React Lifecycle Phases:

  1. Mounting – Component is created and inserted into 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 (Before React Hooks)

Key Lifecycle Methods:

Lifecycle Phase Method Purpose
Mounting constructor() Initialize state and bind methods
Mounting componentDidMount() Run after first render (e.g., fetch data)
Updating componentDidUpdate() Called after re-render (due to state/prop)
Unmounting componentWillUnmount() Cleanup before component is removed

✅ Example:

import React, { Component } from 'react';

class Timer extends Component {
  constructor() {
    super();
    this.state = { seconds: 0 };
  }

  componentDidMount() {
    // Start timer
    this.interval = setInterval(() => {
      this.setState((prev) => ({ seconds: prev.seconds + 1 }));
    }, 1000);
  }

  componentDidUpdate() {
    console.log("Component updated:", this.state.seconds);
  }

  componentWillUnmount() {
    clearInterval(this.interval); // Cleanup
  }

  render() {
    return <h2>Seconds: {this.state.seconds}</h2>;
  }
}

⚡ React Lifecycle with Functional Components (Using Hooks)

React Hooks introduced useEffect() to handle side effects and lifecycle-like behavior in functional components.

useEffect Hook Syntax:

useEffect(() => {
  // Code runs on mount

  return () => {
    // Optional cleanup runs on unmount
  };
}, [dependencies]);

✅ Example with useEffect:

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

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    // Start timer on mount
    const interval = setInterval(() => {
      setSeconds((prev) => prev + 1);
    }, 1000);

    // Cleanup on unmount
    return () => clearInterval(interval);
  }, []); // Empty dependency array = run once

  return <h2>Seconds: {seconds}</h2>;
}

Life Cycle Method Mapping: Class vs Functional

Lifecycle Phase Class Component Functional Component
Mounting componentDidMount() useEffect(() => {}, [])
Updating componentDidUpdate() useEffect(() => {}, [deps])
Unmounting componentWillUnmount() return () => {} inside useEffect

Full Functional Code Example (Mount → Update → Unmount)

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

function Message({ show }) {
  useEffect(() => {
    console.log("Component mounted");

    return () => {
      console.log("Component unmounted");
    };
  }, []);

  useEffect(() => {
    console.log("Component updated");
  });

  return <h3>This is a lifecycle demonstration</h3>;
}

function App() {
  const [visible, setVisible] = useState(true);

  return (
    <div style={{ padding: '2rem' }}>
      <button onClick={() => setVisible(!visible)}>
        {visible ? 'Hide' : 'Show'} Message
      </button>
      {visible && <Message />}
    </div>
  );
}

export default App;

✅ This app demonstrates mounting, updating, and unmounting using useEffect.


Tips & Common Pitfalls

✅ Best Practices

  • Use useEffect wisely: don't put expensive logic inside it without dependencies.

  • Always cleanup timers, listeners, or subscriptions inside the cleanup function.

  • Split multiple concerns into multiple useEffect hooks for clarity.

  • Prefer functional components with hooks for most use cases.

❌ Common Mistakes

  • ❌ Forgetting to provide a dependency array in useEffect (causes infinite loops)

  • ❌ Updating state inside componentDidUpdate or useEffect without condition—leads to re-render loop

  • ❌ Using class lifecycle methods and hooks in the same component (not allowed)


React Lifecycle Comparison Table

Feature Class Component Functional with Hooks
Complexity More verbose Simpler & declarative
Lifecycle methods Built-in methods useEffect covers all cases
Code reuse Difficult Easy with custom hooks
Community trend Declining Highly encouraged

Conclusion: Mastering the React Lifecycle

Understanding the React component lifecycle helps you write code that is efficient, reliable, and maintainable. Whether you use class components or functional ones with hooks, lifecycle control gives you the power to:

  • Fetch data at the right time

  • Manage subscriptions or timers

  • Perform cleanups

  • React to prop or state changes

Key Takeaway: Use useEffect to manage side effects smartly and cleanly. Mastering lifecycle behavior = mastering React.


Key Takeaways

  • React components go through mount → update → unmount

  • useEffect replaces class lifecycle methods

  • Clean up side effects to avoid memory leaks

  • Always define dependencies in hooks properly