Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What are React Lifecycle Methods?

React is a fantastic and popular JavaScript library for building user interfaces. It enables developers to create reusable components that adapt to the changes in data, making the UI more interactive and dynamic. One of the key features of React is its component-based architecture, which allows developers to break down complex UI into smaller, more manageable pieces.

In this blog post, we'll take a deep dive into the concept of lifecycle methods in React. We'll discuss what they are, why they are important, and how to use them effectively when building React applications.

Table of Contents

  1. Understanding React Components
  2. What are Lifecycle Methods?
  3. Lifecycle Methods in React
  4. Mounting
  5. Updating
  6. Unmounting
  7. Using Lifecycle Methods
  8. Conclusion

Understanding React Components

Before we dive into the concept of lifecycle methods, it's essential to have a basic understanding of React components. In React, a component is a self-contained piece of code that represents a part of the user interface. Components can be thought of as building blocks that can be combined to create a complete UI.

There are two types of components in React:

  1. Functional components: These are simple JavaScript functions that take props as input and return JSX (JavaScript XML), which describes the UI to be rendered. Functional components are also known as stateless components as they do not have any internal state.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
  1. Class components: These are JavaScript classes that extend the React.Component class. Class components can have internal state and also have access to lifecycle methods, which allow you to perform specific actions at different stages of a component's life.
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

In this post, we'll focus on class components and their lifecycle methods.

What are Lifecycle Methods?

Lifecycle methods are special methods in class components that allow you to execute code at specific points during the component's life. These methods are called automatically by React during the process of rendering, updating, and unmounting components.

Imagine a component's life as a series of events or stages, such as being created, mounted on the DOM, updated due to changes in props or state, and eventually unmounted and removed from the DOM. Lifecycle methods act as hooks that allow you to perform actions before or after these stages.

Using lifecycle methods, you can add side effects, fetch data from an API, manipulate the DOM, and more. Properly handling these actions can lead to better performance, cleaner code, and a more optimized user experience.

Lifecycle Methods in React

React provides a set of lifecycle methods that you can use to manage the different stages of a component's life. These methods are divided into three main categories: mounting, updating, and unmounting.

Mounting

Mounting refers to the process of inserting a component into the DOM. When a component is mounted, the following lifecycle methods are called in the given order:

  1. constructor: This method is called when the component is first created. It is typically used to set up the initial state of the component and bind event handlers.
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this);
  }
}
  1. static getDerivedStateFromProps: This method is called before the component is rendered and allows you to derive the component's state from its props. It is a static method, meaning it doesn't have access to the component's instance.
class Timer extends React.Component {
  static getDerivedStateFromProps(props, state) {
    // Return an object with the updated state or null if no changes are needed
    return { timeRemaining: props.initialTime - state.elapsedTime };
  }
}
  1. render: This method is responsible for returning the JSX that defines the component's UI. It is the only required lifecycle method in a class component.
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
  1. componentDidMount: This method is called after the component has been rendered and inserted into the DOM. It is a good place to perform actions that require the component to be present in the DOM or to fetch data from an API.
class UserProfile extends React.Component {
  componentDidMount() {
    // Fetch user data from an API
    getUserData(this.props.userId).then((data) => this.setState({ userData: data }));
  }
}

Updating

Updating occurs when a component's props or state changes, causing the component to re-render. When a component updates, the following lifecycle methods are called in the given order:

static getDerivedStateFromProps: This method is called before the component is re-rendered and allows you to derive the component's state from its props, just like during mounting.

shouldComponentUpdate: This method is used to determine if the component should re-render when its props or state change. By default, it always returns true, but you can override it to implement your own logic and optimize the rendering process.

class DataList extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    // Only update the component if the data has changed
    return nextProps.data !== this.props.data;
  }
}

render: This method is called again to render the updated component.

getSnapshotBeforeUpdate: This method is called right before the updated component is committed to the DOM. It allows you to capture information from the DOM before it is updated, such as scroll position or selected text.

class ChatWindow extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Capture the current scroll position before the component is updated
    const scrollPosition = this.chatWindow.scrollTop;
    return { scrollPosition };
  }
}
  1. componentDidUpdate: This method is called after the updated component has been committed to the DOM. It is a good place to perform side effects or fetch data based on the updated props or state.
class UserProfile extends React.Component {
  componentDidUpdate(prevProps) {
    if (this.props.userId !== prevProps.userId) {
      // Fetch new user data if the user ID has changed
      getUserData(this.props.userId).then((data) => this.setState({ userData: data }));
    }
  }
}

Unmounting

Unmounting refers to the process of removing a component from the DOM. When a component is unmounted, the following lifecycle method is called:

  1. componentWillUnmount: This method is called just before the component is removed from the DOM. It is a good place to perform cleanup actions, such as removing event listeners or canceling network requests.
class Clock extends React.Component {
  componentWillUnmount() {
    // Clear the interval when the component is unmounted
    clearInterval(this.timerID);
  }
}

Using Lifecycle Methods

Now that we've covered the different lifecycle methods in React, let's see how they can be used in practice with a simple example.

Consider a Clock component that displays the current time and updates every second. Here's how we can build this component using lifecycle methods:

  1. In the constructor, we set up the initial state of the component with the current time.
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentTime: new Date() };
  }
}
  1. In the render method, we return the JSX that displays the current time.
class Clock extends React.Component {
  // ...
  render() {
    return <h1>{this.state.currentTime.toLocaleTimeString()}</h1>;
  }
}
  1. In the componentDidMount method, we set up a timer that updates the current time every second.
class Clock extends React.Component {
  // ...
  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  tick() {
    this.setState({ currentTime: new Date() });
  }
}
  1. In the componentWillUnmount method, we clear the timer to prevent memory leaks.
class Clock extends React.Component {
  // ...
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
}

With the Clock component complete, it will now display the current time and update every second, thanks to the proper use of lifecycle methods.

Conclusion

In this blog post, we've explored the concept of lifecycle methods in React and how they can be used to manage the different stages of a component's life. Understanding and using lifecycle methods effectively is crucial for building efficient, dynamic, and interactive React applications.

Remember that lifecycle methods act as hooks that allow you to perform actions at specific points during a component's life, such as mounting, updating, and unmounting. By using these methods, you can optimize your components' performance, manage side effects, fetch data, and more.

As you continue to work with React and build more complex applications, you'll find that mastering lifecycle methods is an invaluable skill that will help you create better, more efficient components.