React Class Component Lifecycle Methods

As a React developer with over a decade of experience, I’ve seen firsthand how understanding the lifecycle of class components can drastically improve your app’s performance and maintainability.

React class components go through specific phases during their existence, and knowing when and how to hook into these phases lets you control your component’s behavior effectively.

In this guide, I’ll walk you through the essential lifecycle methods in React class components. I’ll share practical examples and tips, making it easy for you to grasp these concepts, even if you’re just starting or want to deepen your understanding.

What Are React Class Component Lifecycle Methods?

Every React class component has a lifecycle, meaning it goes through different stages from creation to removal. These stages are:

  • Mounting: When the component is being inserted into the DOM.
  • Updating: When the component is re-rendered due to changes in props or state.
  • Unmounting: When the component is removed from the DOM.

React provides lifecycle methods that let you run code at these key moments. This control helps with tasks such as fetching data, setting up subscriptions, or cleaning up resources.

Mount Phase Methods

The mounting phase happens once when the component is first added to the DOM. Here are the key methods:

1. constructor(props)

This is the first method called. It’s used to initialize state and bind event handlers.

constructor(props) {
  super(props);
  this.state = { count: 0 };
  this.handleClick = this.handleClick.bind(this);
}

2. componentDidMount()

This runs after the component is mounted. It’s perfect for fetching data or setting up timers.

componentDidMount() {
  console.log('Component mounted');
  // Example: Fetch data from an API
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => this.setState({ data }));
}

You can refer to the screenshot below to see the output:

Class Component Lifecycle Methods React

Update Phase Methods

Updating happens when props or state change, triggering a re-render.

3. shouldComponentUpdate(nextProps, nextState)

Use this to optimize performance by preventing unnecessary renders. Return true to update, false to skip.

shouldComponentUpdate(nextProps, nextState) {
  return nextState.count !== this.state.count;
}

4. componentDidUpdate(prevProps, prevState)

Called after the component updates. Useful for reacting to prop or state changes.

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

You can refer to the screenshot below to see the output:

Class Component Lifecycle Methods in React

Unmount Phase Method

Here are some unmount phase methods:

5. componentWillUnmount()

This runs just before the component is removed from the DOM. Use it to clean up timers, subscriptions, or event listeners.

componentWillUnmount() {
  clearInterval(this.timerID);
  console.log('Component will unmount');
}

Full Example: USA Weather Dashboard Component

Let me show you a practical example. Imagine you’re building a weather dashboard for a US city. You want to fetch weather data when the component mounts, update it when the city changes, and clear any intervals when the component unmounts.

import React, { Component } from 'react';

class WeatherDashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      weather: null,
      city: 'New York',
      loading: true,
    };
    this.updateWeather = this.updateWeather.bind(this);
  }

  componentDidMount() {
    this.updateWeather();
    // Refresh weather every 10 minutes
    this.timerID = setInterval(this.updateWeather, 600000);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.city !== this.state.city) {
      this.updateWeather();
    }
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  updateWeather() {
    this.setState({ loading: true });
    fetch(`https://api.weather.gov/gridpoints/OKX/33,37/forecast`)
      .then(response => response.json())
      .then(data => {
        this.setState({
          weather: data.properties.periods[0],
          loading: false,
        });
      })
      .catch(error => {
        console.error('Error fetching weather:', error);
        this.setState({ loading: false });
      });
  }

  render() {
    const { weather, loading, city } = this.state;

    return (
      <div>
        <h2>Weather Dashboard - {city}</h2>
        {loading && <p>Loading weather data...</p>}
        {weather && !loading && (
          <div>
            <p><strong>Temperature:</strong> {weather.temperature}°{weather.temperatureUnit}</p>
            <p><strong>Forecast:</strong> {weather.shortForecast}</p>
          </div>
        )}
        <button onClick={() => this.setState({ city: 'Los Angeles' })}>
          Switch to Los Angeles
        </button>
      </div>
    );
  }
}

export default WeatherDashboard;

You can refer to the screenshot below to see the output:

React Class Component Lifecycle Methods

In this example, I use:

  • constructor to initialize state and bind methods.
  • componentDidMount to fetch weather data and start an interval.
  • componentDidUpdate to fetch new data when the city changes.
  • componentWillUnmount to clear the interval.

This pattern ensures your component stays up-to-date and cleans up resources properly.

Additional Tips from Experience

  • Avoid heavy computations inside render(). Use lifecycle methods to handle side effects.
  • Always clean up in componentWillUnmount to prevent memory leaks.
  • Use shouldComponentUpdate wisely to improve performance, especially in large apps.
  • Remember, React is moving towards hooks and functional components, but understanding class lifecycle methods remains valuable for maintaining legacy code.

I hope this guide helps you master React class component lifecycle methods. With these tools, you can build robust, efficient React applications that behave exactly as you want at every stage of their lifecycle.

Related Articles You May Like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.