Component Lifecycle Methods in React

Expert-Level Explanation

Component lifecycle methods in React are specialised functions that get called at different stages of a component's life. They can be categorised into mounting, updating, and unmounting phases:

  • Mounting: When a component is being created and inserted into the DOM. Key methods are constructor, render, and componentDidMount.

  • Updating: This occurs when a component's props or state change. Key methods include render, shouldComponentUpdate, getSnapshotBeforeUpdate, and componentDidUpdate.

  • Unmounting: When a component is being removed from the DOM. The key method iscomponentWillUnmount.

These methods are used for various tasks like initialising states, making API calls, setting up subscriptions, and cleaning up resources.

Creative Explanation

Imagine a component's lifecycle like the life of a plant. Mounting is like planting a seed in the soil (a component being inserted into the DOM). Updating is like nurturing the plant with water and nutrients (responding to prop and state changes). Finally, unmounting is like removing the plant when it's no longer needed (a component being removed from the DOM). Throughout its life, the plant (component) goes through various stages where it needs different care (lifecycle methods).

Practical Explanation with Code

Here's an example using some lifecycle methods in a class component:

import React, { Component } from 'react';

class User extends Component {
  constructor(props) {
    super(props);
    this.state = { user: null };
  }

  componentDidMount() {
    // Fetch user data after component is mounted
    fetchUser(this.props.userId).then(user => this.setState({ user }));
  }

  componentDidUpdate(prevProps) {
    // Update user data if userId prop changes
    if (this.props.userId !== prevProps.userId) {
      fetchUser(this.props.userId).then(user => this.setState({ user }));
    }
  }

  componentWillUnmount() {
    // Clean up tasks
    cancelFetchUser(this.props.userId);
  }

  render() {
    const { user } = this.state;
    return user ? <div>{user.name}</div> : <div>Loading...</div>;
  }
}

export default User;

In this example, componentDidMount fetches user data when the component mounts. componentDidUpdate updates the data when props change. componentWillUnmount handles cleanup.

Real-World Example

In a chat application, when a user opens a conversation, a Chat component mounts, initiating a connection to a server to receive messages (componentDidMount). As the user sends or receives messages (state changes), the component updates to display the latest messages (componentDidUpdate). When the user exits the chat, the component unmounts, closing the connection to the server (componentWillUnmount). This lifecycle management ensures efficient resource usage and real-time updates.

Did you find this article valuable?

Support Akash Thoriya by becoming a sponsor. Any amount is appreciated!