ReactJS - componentDidUpdate() Method



Nowadays React has become a popular library for creating dynamic and interactive user interfaces. A fundamental feature of React is lifecycle methods, which allow developers to control the behavior of components across their lifetimes. So we will concentrate on the componentDidUpdate lifecycle method.

What is componentDidUpdate?

componentDidUpdate is a React function that is called when our component is re-rendered with new data. Assume that anything has changed in our component and that we want to respond to those changes. It is similar to a post-update notification.

It is important to know that componentDidUpdate is not called when the component is created for the first time. It is only called after the first rendering when something in our component changes, such as receiving new data or props.

Syntax

componentDidUpdate(prevProps, prevState)

Parameters

  • prevProps − This is a snapshot of our component's properties before updating. Consider it a record of what the component looked like before it changed. We can compare this to our current props to see what is changed.

  • prevState − This is a snapshot of the component's state before the change, similar to prevProps. It is similar to recording the state of our component just before it changes.

Return Value

The componentDidUpdate method does not return anything.

Why componentDidUpdate!

This method helps when we need to change the text of a web page, handle network requests, or adjust the state of a component based on new data after an update.

For example we are creating a chat app. So when a user changes to a different chat room or if the URL is changed, we will have to perform some actions like disconnecting from the current chat and connecting to the new one. So in that case componentDidUpdate is the right choice for that.

Examples

Example − Counter App

Now we will make use of the componentDidUpdate function. In this example, we are going to create a counter app that allows the user to increase or decrease the value of a counter. We will use componentDidUpdate to see if the counter value has changed and then display a message if it has changed.

import React, { Component } from "react";

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         counter: 0,
         message: ""
      };
   }   
   componentDidMount() {
      this.updateMessage();
   }   
   componentDidUpdate(prevProps, prevState) {
      if (this.state.counter !== prevState.counter) {
         this.updateMessage();
      }
   }   
   updateMessage() {
      if (this.state.counter % 2 === 0) {
         this.setState({
            message: "Counter is even!"
         });
      } else {
         this.setState({
            message: "Counter is not even."
         });
      }
   }      
      incrementCounter = () => {
         this.setState((prevState) => ({
            counter: prevState.counter + 1
         }));
      };
      
      decrementCounter = () => {
      this.setState((prevState) => ({
         counter: prevState.counter - 1
      }));
   };
   
   render() {
      return (
         <div>
            <h1>Counter Example</h1>
            <p>Counter: {this.state.counter}</p>
            <button onClick={this.incrementCounter}>Increment</button>
            <button onClick={this.decrementCounter}>Decrement</button>
            <p>{this.state.message}</p>
         </div>
      );
   }
}

export default App;

Output

counter example

When we execute the application, we will see two buttons, one for incrementing and one for decrementing. When we click the increment or decrement button to increase or decrease the counter, the message changes depending on whether the counter is even or odd. This shows how componentDidUpdate is used to respond to changes in the component's state and take the necessary action.

Example − Display Updated Data

This app shows the use of componentDidUpdate to respond to changes in the component's state, specifically when the data is updated. So we will initialize with an initial data state. And then display the data on the webpage. Also we will provide a button to update the data. So when the data is updated, it logs a message to the console.

import React, { Component } from 'react';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         data: 'Initial Data',
      };
   }   
   componentDidUpdate(prevProps, prevState) {
      if (prevState.data !== this.state.data) {
         console.log('Data updated:', this.state.data);
      }
   }   
   updateData = () => {
      this.setState({ data: 'Updated Data' });
   };   
   render() {
      return (
         <div>
            <h1>{this.state.data}</h1>
            <button onClick={this.updateData}>Update Data</button>
         </div>
      );
   }
}

export default App;

Output

initial update data

Example − Dynamic Title App

This app shows how componentDidUpdate can be used to dynamically update the title of the document as per the changes in the component's state. So we will first initialize with an initial page title state. And then we will display the page title on the webpage. And then we will provide a button to change the title. When the title is updated, it dynamically changes the document title, and this change is logged to the console.

import React, { Component } from 'react';

class App extends Component {
   constructor(props) {
      super(props);
      this.state = {
         pageTitle: 'Initial Title',
      };
   }   
   componentDidUpdate(prevProps, prevState) {
      if (prevState.pageTitle !== this.state.pageTitle) {
         document.title = this.state.pageTitle;
      }
   }   
   updateTitle = () => {
      this.setState({ pageTitle: 'New Title' });
   };   
   render() {
      return (
         <div>
            <h1>{this.state.pageTitle}</h1>
            <button onClick={this.updateTitle}>Change Title</button>
         </div>
      );
   }
}

export default App;

Output

initial title

Notes

  • If we want to prevent componentDidUpdate from being called, use the shouldComponentUpdate function and return false. This is useful if we need to control when updates occur.

  • Make sure to avoid creating infinite loops. We should utilize conditions in componentDidUpdate to determine whether we really need to do anything after the update. If we avoid this, our component might continue to update indefinitely.

  • If possible, avoid using setState within componentDidUpdate. It can cause an extra rendering, which can have an effect on performance in certain cases.

Summary

componentDidUpdate is a React function that is called after our component updates. It is like a message showing something in our component has changed, and we can react to that change. We can select what to do next by comparing previous data (props and state) with the present data.

reactjs_reference_api.htm
Advertisements