Lecture Notes Of Day 10: Component Lifecycle (Class Components)

Rashmi Mishra
0

 

Lecture Notes Of Day 10: Component Lifecycle (Class Components)

Objective:

To understand the lifecycle methods in React class components, including componentDidMount, componentWillUnmount, and the render method.

Outcome:

By the end of this class, students will be able to:

1.  Understand what lifecycle methods are and how they are used in React class components.

2.  Learn about the three main lifecycle methods: componentDidMount, componentWillUnmount, and render.

3.  Apply these methods to manage side effects, optimize rendering, and clean up resources.


Introduction to React Component Lifecycle

In React, class components have a lifecycle. The lifecycle of a component refers to the different stages a component goes through from the time it is created to when it is destroyed. Understanding the lifecycle methods is important because they allow you to perform certain actions at different points in a component's life, such as fetching data, performing setup tasks, or cleaning up resources.

React components go through the following stages:

1.  Mounting: When a component is created and inserted into the DOM.

2.  Updating: When a component's state or props change.

3.  Unmounting: When a component is removed from the DOM.

Each stage has its own set of lifecycle methods that are called automatically by React. The most common lifecycle methods used in class components are:

  • constructor
  • render
  • componentDidMount
  • componentDidUpdate
  • componentWillUnmount

For today's lesson, we will focus on the render, componentDidMount, and componentWillUnmount methods.


1. The render Method

The render method is required in all React class components. It is the method that defines what the UI will look like for the component. This method returns the JSX that React will use to update the DOM. It is called automatically every time the component’s state or props change, triggering a re-render.

Key Points about render:

  • It returns JSX (or null).
  • It should not have side effects. Side effects should be handled in other lifecycle methods.
  • It can access the component's state and props.

Example of the render method:

jsx

Copy code

class Welcome extends React.Component {

  constructor(props) {

    super(props);

    this.state = { name: 'John' };

  }

 

  render() {

    return <h1>Hello, {this.state.name}!</h1>;

  }

}

In the above example:

  • The render method returns the JSX that displays a greeting message.
  • Whenever the state changes (e.g., the name), React will re-run the render method to update the DOM.

2. The componentDidMount Method

The componentDidMount method is called once, immediately after the component is added to the DOM. This is the perfect place to perform side effects such as:

  • Fetching data from an API.
  • Setting up subscriptions (like websockets).
  • Manipulating the DOM.

This method is only called once during the lifecycle (when the component is mounted).

Key Points about componentDidMount:

  • It is called once after the component is first mounted.
  • It is useful for fetching data, subscribing to external data sources, and setting up things that the component needs.

Example of using componentDidMount:

jsx

Copy code

class User extends React.Component {

  constructor(props) {

    super(props);

    this.state = { userData: null };

  }

 

  componentDidMount() {

    // Fetching data after the component mounts

    fetch('https://api.example.com/user')

      .then(response => response.json())

      .then(data => this.setState({ userData: data }));

  }

 

  render() {

    if (!this.state.userData) {

      return <div>Loading...</div>;

    }

    return <div>{this.state.userData.name}</div>;

  }

}

In this example:

  • When the User component is mounted, the componentDidMount method is triggered.
  • It fetches user data from an API and updates the component’s state, which triggers a re-render.

3. The componentWillUnmount Method

The componentWillUnmount method is called just before the component is removed from the DOM. This is where you should clean up any resources or subscriptions that the component created. For example:

  • Clearing timers (like setInterval or setTimeout).
  • Removing event listeners.
  • Closing network requests or connections (like WebSockets).

Key Points about componentWillUnmount:

  • It is called before the component is removed from the DOM.
  • It is used for cleanup to prevent memory leaks or unwanted side effects.

Example of using componentWillUnmount:

jsx

Copy code

class Timer extends React.Component {

  constructor(props) {

    super(props);

    this.state = { time: 0 };

    this.timerID = null;

  }

 

  componentDidMount() {

    // Set up a timer when the component mounts

    this.timerID = setInterval(() => this.tick(), 1000);

  }

 

  componentWillUnmount() {

    // Clear the timer when the component is about to unmount

    clearInterval(this.timerID);

  }

 

  tick() {

    this.setState(prevState => ({

      time: prevState.time + 1

    }));

  }

 

  render() {

    return <h1>Time: {this.state.time}s</h1>;

  }

}

In this example:

  • The componentDidMount method sets up a timer to update the state every second.
  • The componentWillUnmount method clears the timer when the component is removed, preventing memory leaks.

Recap of Lifecycle Methods

Method

When It’s Called

Use Case

render

Every time the component re-renders

Returns JSX to display the component UI.

componentDidMount

After the component has been mounted (added to the DOM)

Perform initial setup tasks like fetching data or adding event listeners.

componentWillUnmount

Just before the component is unmounted (removed from the DOM)

Clean up resources such as timers, subscriptions, or event listeners.


Practical Application

1.  Handling API Requests: Use componentDidMount to fetch data from an API after the component is loaded, and update the state to trigger re-renders with the new data.

2.  Setting Up Timers and Intervals: Use componentDidMount to set up intervals (e.g., for a clock or live updates) and componentWillUnmount to clear them to avoid memory leaks.

3.  Cleaning up Subscriptions: If your component listens to a WebSocket or event listeners, use componentDidMount to set them up and componentWillUnmount to remove them.


Conclusion

The lifecycle methods in class components are essential tools that allow you to control when and how to interact with the component. Understanding componentDidMount, componentWillUnmount, and render will help you manage side effects, optimize performance, and clean up after your components, making your React applications more efficient and scalable.

Homework / Assignment

1.  Exercise 1: Create a class component that fetches data from a mock API (use https://jsonplaceholder.typicode.com/posts) and displays a list of posts. Use componentDidMount for fetching the data.

2.  Exercise 2: Create a timer component that starts counting seconds when mounted. Ensure to clear the timer in componentWillUnmount to prevent it from running after the component is unmounted.


Post a Comment

0Comments

Post a Comment (0)