React Mastery / React Core Concepts

Component Lifecycle

🧩 What is a Component in React?

Think of a React component like a reusable piece of UI. For example:

  • A button on your webpage can be a component.

  • A navigation bar is a component.

  • A form can be another component.

You can create these components either using:

  • Class components (older style)

  • Function components (modern way using Hooks)

This explanation is focused on Class Components and how they live their life – just like a human! 🎯


🧬 What is a Lifecycle?

Every component in React goes through a life:

  1. It is born β†’ added to the webpage

  2. It lives β†’ updates when needed

  3. It dies β†’ removed from the webpage

These steps are called the Component Lifecycle.



🟦 1. Mounting (When the component is created and added to the screen)

Mounting means when a component is created and shown on the screen for the first time.

Mounting Lifecycle Flow (in order)

constructor β†’ render β†’ componentDidMount

(Some methods exist in between, but these are the most important)

🧠 Think of it like entering a movie theatre:

  • First, the lights and seats are prepared (setup before anything shows)

  • Then, the screen turns on (UI appears)

  • Finally, the movie starts playing (data loads, effects run)

Mapping to React Mounting πŸ‘‡

  • 🎬 Setup seats & lights β†’ constructor()

  • πŸ“Ί Screen turns on β†’ render()

  • ▢️ Movie starts β†’ componentDidMount()

Lifecycle methods used:

Method

What it does

Easy Explanation

constructor()

Initializes state and binds methods

Setting things up before the component appears

getDerivedStateFromProps()

Syncs state with props (rare)

Adjust state if props change before rendering

render()

Returns JSX (UI)

Decides what appears on the screen

componentDidMount()

Runs after UI is visible

Best place to fetch API data

βœ… Example:

import React from "react";

class UserProfile extends React.Component {
  constructor(props) {
    super(props);

    // Step 1: Setup initial state
    this.state = {
      name: "Loading..."
    };
  }

  // Step 3: Called AFTER component appears on screen
  componentDidMount() {
    // Simulating API call
    setTimeout(() => {
      this.setState({ name: "Codeveda" });
    }, 2000);
  }

  // Step 2: Shows UI on screen
  render() {
    return <h1>Hello, {this.state.name}</h1>;
  }
}

export default UserProfile;

πŸ“Œ Key Takeaways

βœ” Mounting = first time component appears

βœ” render() is mandatory

βœ” componentDidMount() is perfect for API calls

βœ” constructor() is for initial setup only


🟨 2. Updating (When the component changes and re-renders)

The updating phase happens when a component is already on the screen, but something changes.

This change can happen because:

  • State changes (setState)

  • Props change (new data from parent)

🧠 Think of it like changing channels on a TV:

  • The TV is already ON

  • You press the remote button

  • The screen updates with a new channel

The TV doesn’t restart β€” only the content changes.

Updating Lifecycle Flow

Props / State Change
        ↓
getDerivedStateFromProps()
        ↓
shouldComponentUpdate()
        ↓
render()
        ↓
componentDidUpdate()

Lifecycle Methods

Method

What it does

Easy Explanation

constructor()

Initializes state and binds methods

Setting things up before the component appears

getDerivedStateFromProps()

Syncs state with props (rare)

Adjust state if props change before rendering

render()

Returns JSX (UI)

Decides what appears on the screen

componentDidMount()

Runs after UI is visible

Best place to fetch API data

βœ… Example

import React from "react";

class Counter extends React.Component {
  state = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      console.log("Count updated:", this.state.count);
    }
  }

  render() {
    return (
      <div>
        <h2>Count: {this.state.count}</h2>
        <button onClick={this.increment}>Increase</button>
      </div>
    );
  }
}

export default Counter;

πŸ“Œ Key Takeaways

βœ” Updating happens when state or props change

βœ” render() runs again

βœ” componentDidUpdate() is good for side effects

βœ” Avoid calling setState() blindly inside componentDidUpdate()


πŸŸ₯ 3. Unmounting (When the component is removed from the screen)

The unmounting phase happens when a component is removed from the screen.

This usually happens when:

  • You navigate to another page

  • A condition becomes false

  • A component is no longer needed

What does componentWillUnmount() do?

Purpose

Simple Explanation

Cleanup

Remove timers, listeners, subscriptions

Prevent memory leaks

Stop things running in background

Final step

Component will never render again

Lifecycle method used:

Method

What it does

Simple Explanation

componentWillUnmount()

Runs right before the component is removed.

Good place to clean up timers or stop API calls.

βœ… Example:

import React from "react";

class Timer extends React.Component {
  componentDidMount() {
    this.interval = setInterval(() => {
      console.log("Timer running...");
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
    console.log("Timer stopped");
  }

  render() {
    return <h2>Timer is running</h2>;
  }
}

export default Timer;

🚨 Important Rules

❌ Do NOT call setState() here

❌ Do NOT fetch data here

βœ” Only cleanup logic belongs here