Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

React componentDidUpdate() Method [A Beginner's Guide]

Updated on 28 October, 2024

18.21K+ views
13 min read

React is a powerful view library that helps you build user interfaces. In addition to its stand-out functionalities, React also offers several methods that make development easier, including the ability to use components. Components are an integral part of React development that allows for breaking the user interface into smaller, more manageable chunks. Web development enthusiasts looking forward to mastering React must dive deep into React methods and component topics.  

Out of the four built-in methods in React — constructor(), getDerivedStateFromProps(), render() and componentDidMount (), the componentDidUpdate() method is most commonly used in web development projects. This blog will look at how you can use the componentDidUpdate lifecycle method in React components. Also, we will dive deep into some of the benefits of using React componentDidUpdate and its examples.  

Let's Start!

What is React componentDidUpdate?

ComponentDidUpdate is a React component lifecycle method invoked immediately after a component's updates are flushed to the DOM. This is one of the most used built-in methods, which is not called for the initial render nor applicable to your functional details.

However, this method is useful for setting states based on props changes or performing side-effects such as fetching data from an API. Also, you can use React hooks for functional components to achieve the same functionality.

Syntax of React componentDidUpdate()

componentDidUpdate(prevProps, prevState, snapshot)

Let’s define the parameters used in the componentDidUpdate function:

  • prevProps: This is the first argument, and it passes the previous props to the component.
  • prevState: This is the second argument, and it passes the previous state of the component.
  • snapshot: Returns value using the getSnapshotBeforeUpdate() method.

Take a look at an example of how componentDidUpdate is used to set the state based on the modifications made on props:

class MyComponent extends React. Component
{
    componentDidUpdate(prevState, prevProps)
    {
      // Access props with this.props

      // Access state with this.state
     
      // prevState contains state before update
      // prevProps contains props before update
    }
 render() {
      return <div></div>;
    }
}

Note that you should not call setState() in componentDidUpdate() hooks. Calling the setState() function will cause a rerender of the component and also lead to performance issues. If you need to set state based on props changes, use componentWillReceiveProps() instead. Assuming you need to work on something while the initial rendering, use the componentDidMount() function instead.

To learn more about React and know the flow of learning React from the start, you can check the React JS syllabus for our courses.

Medium

When Does React ComponentDidUpdate Get Called?

The React Component Did Update method gets called after a component has been updated. It is invoked immediately after updating occurs and not before. This means that even if you set the state in this method, it will not trigger another update,

There are several use cases for this lifecycle method:

  • You can access the previous React props and state of the component by passing in the arguments `pre props` and `private`. This can be helpful for comparison purposes or if you need to make sure that certain values have changed before acting.
  • You can call setState here, which will trigger an update to the component. However, be aware that this will create an infinite loop if not used properly.
  • You can perform side effects here, such as making an API call or setting up a subscription. Just be sure to clean up any side effects before the component unmounts.

When to Use React componentDidUpdate Hook?

There are a few situations where the componentDidUpdate capacity can be useful.

1. Working with DOM

In this section, we’ll walk through the use of componentDidUpdate when working with DOM. We’ll get the component’s positioning, orientation, and dimensioning using DOM nodes. Also, we have an option to initialise an animation or pass the underlying DOM node to third-party non-React libraries.

Here, we will access the underlying DOM nodes of React components using this function. Let’s understand with the help of an example where the size the box will get updated every the "Resize" button is clicked:

class MyComponent extends React.Component {
   constructor(props) {
     super(props);
     this.state = { size: 100 };
     this.boxRef = React.createRef();
   }
 handleIncrementClick = () => {
     // set new state to force update
     this.setState((state, props) => ({ size: state.size + 10 }));
   };
componentDidUpdate(prevState, prevProps) {
     // react to update and change the HTML element's size
     this.boxRef.current.style.width = `${this.state.size}px`;
     this.boxRef.current.style.height = `${this.state.size}px`;
   }
  render() {
     return (
       <div>
         <button onClick={this.handleIncrementClick}>Resize</button>
         <div ref={this.boxRef}></div>
       </div>
     );
   }
}

Explanation 

We have a component that acts as a storage house and keeps the record of the size value. On clicking the "Resize" button, the function handleIncrementClick increments the size by 10, and simultaneously the state is changed via the setState function. As a result, the component gets updated. 

Note: 

Every time the “Resize” button is clicked and the setState function is called, the componentDidUpdate function starts running, and the component gets updated. Also, you can use componentDidUpdate to get the ref to the div DOM element and adjust the basic dimensional properties like width and height.

2. Requesting Data from the Server

The function componentDidUpdate is also helpful when fetching data from a server. That means you can use componentDidUpdate to fetch data from a targeted server or API 

Let’s understand with the help of an example where we will pull data from a server.  A user will have a list of projects, and the name of an individual user will be selected using buttons, while a list of user's projects will be fetched from a server. 

In the parent MyComponent component, there are two buttons - one for selecting the name of the user and the other ProjectsComponent component to show the list of projects.

class MyComponent extends React.Component { 
   constructor(props) { 
     super(props); 
     this.state = { client: '' }; 
   } 
setMichael = () => { 
     this.setState({ client: 'Michael' }); 
   }; 
 setNora = () => { 
     this.setState({ client: 'Nora' }); 
   }; 
render() { 
     return ( 
       <div> 
         <button onClick={this.setMichael}>Michael</button> 
         <button onClick={this.setNora}>Nora</button> 
         <ProjectsComponent client={this.state.client} /> 
       </div> 
     ); 
   } 
 } 
 // We will implement this component shortly 
 class ProjectsComponent extends React.Component { 
... 
 }

In our example, the MyComponent is the parent component, and the child is the ProjectsComponent. The parent component stores the client’s details and passes them to the child component. As the client values get updated, the child gets notified and receives new props 

Let's implement the ProjectsComponent showing a list of projects for a selected user:

class ProjectsComponent extends React.Component { 
   constructor(props) { 
     super(props); 
     this.state = { projects: [] }; 
   } 
// Emulate server data fetch. Return data after 300 ms timeout 
   fetchData = client => { 
     setTimeout(() => { 
       this.setState({ 
         projects: 
           client === 'Michael' 
             ? ['Project Aiden', 'Project Brook'] 
             : ['Project Cecilia', 'Project Delta'] 
       }); 
     }, 300); 
   }; 
componentDidUpdate(prevProps, prevState) { 
     // check whether client has changed 
     if (prevProps.client !== this.props.client) { 
       this.fetchData(this.props.client); 
     } 
   } 
render() { 
     // render a list of projects 
     return ( 
       <div> 
         <b>Projects for {this.props.client}</b> 
         <ul> 
           {this.state.projects.map(project => ( 
             <li>{project}</li> 
           ))} 
         </ul> 
       </div> 
     ); 
   } 
 }

By comparing the prevProps and this.props values, we verify the client’s present status. Whenever the client details get updated, we request a list of their projects from a server. On successful receiving the remote data, the component’s state gets updated with a list of projects. 

While we update the component's internal state, it triggers a new update and the componentDidUpdate gets called. Extra attention must be given when using the setState function in the componentDidUpdate because if the values are not set correctly, the code block may run an infinite loop. Verify the name of the client in props to prevent infinite loop:

class ProjectsComponent extends React.Component { 
constructor(props) { 
     super(props); 
     this.state = { projects: [] }; 
   } 
// Emulate server data fetch. Return data after 300 ms timeout 
   fetchData = client => { 
     setTimeout(() => { 
       this.setState({ 
         projects: 
           client === 'Michael' 
             ? ['Project Aiden', 'Project Brook'] 
             : ['Project Cecilia', 'Project Delta'] 
       }); 
     }, 300); 
   }; 
componentDidUpdate(prevProps, prevState) { 
     // check whether client has changed 
     if (prevProps.client !== this.props.client) { 
       this.fetchData(this.props.client); 
     } 
   } 
render() { 
// render a list of projects 
     return ( 
       <div> 
         <b>Projects for {this.props.client}</b> 
         <ul> 
           {this.state.projects.map(project => ( 
             <li>{project}</li> 
           ))} 
         </ul> 
       </div> 
     ); 
   } 
 }

Minimising Updates with shouldComponentUpdate  

Another important area where componentDidUpdate is used is to reduce updates. In React, you can leverage the shouldComponentUpdate function to optimize the component performance. This function gets called before an update resulting in a boost and high performance.   

React takes the result of shouldComponentUpdate into consideration and updates accordingly. By default, the shouldComponentUpdate function returns true to verify an update. However,  you can also override this function and return false if there is no need for updates.   

The shouldComponentUpdate function takes the values of the next properties and next state as arguments. This.props and this.state can be used to access current properties and state. However, the function didComponentUpdate is not called if React skips an update:

class MyComponent extends React.Component { 
   shouldComponentUpdate(nextProps, nextState) { 
     // add condition to check whether need to update 
     // return false to hint React to avoid update 
     if (this.props.name !== nextProps.name) { 
       return false; 
     } 
return true; 
   } 
render() { 
return <div></div>; 
   } 
 }

How to Use React.PureComponent for Performance?

React.PureComponent is mainly used for performance optimization. As React component render() function returns the same result with the identical properties and state, you can use React.PureComponent to improve performance in many cases. Pure components are exactly like regular components except for two things: they implement shouldComponentUpdate() with a shallow comparison of props and state, and they don't support the componentDidUpdate() lifecycle hook. 

Instead of implementing the shouldComponentUpdate function, use React.PureComponent as a base class for the component. React.PureComponent implements shouldComponentUpdate and subtly compares props and state to check if there is a need for an update. When comparing, it takes the props and state objects properties and confirms the equality of the current and the next values.

class MyComponent extends React.PureComponent { 
   // we don't need to implement shouldComponentUpdate 
   // React.PureComponent does that 
render() { 
     return <div></div>; 
   } 
 }

The advantage of using React.PureComponent is that you don't have to worry about accidentally rerendering your component when there's no need to. If you forget to add a shouldComponentUpdate() method to a regular component or write one that always returns true with React.PureComponent, the default behaviour is already optimised for performance. 

Warning Bells! 

There are a few trade-offs to be aware of when using React.PureComponent, though. 

First, because the shouldComponentUpdate() method only makes a shallow comparison of props and state, it won't work well if your component has complex data structures. If you need shouldComponentUpdate() to make a deep comparison, you can write it yourself or use a library like Immutable.js. 

Secondly, Pure components don't support the componentDidUpdate() lifecycle hook. If you need to do any post-processing after a component update, you'll have to do it in the component's update() lifecycle hook instead. 

Examples of Using React componentDidUpdate Hook

Let’s look at the componentDidUpdate examples and how we can use them in our project. 

Example:1 We will build a basic React application that changes the heading text when the component gets updated. 

Step-1: Create a project and call it demoproject:

npx create-react-app demoproject

Step-2:  Move to the current directory using the cd command:

cd functiondemo

Step-3: Add the following block of code to your JavaScript file:

mport React from 'react'; 
class App extends React.Component { 
// Define the state 
state = { 
   company: 'KnowHut' 
}; 
componentDidMount() { 
   // Change the state after 600ms 
   setTimeout(() => { 
   this.setState({ company: 'KnowledgeHut' }); 
   }, 600); 
} 
componentDidUpdate() { 
   document.getElementById('warning').innerHTML = 
   'P.s: KnowHut is also known as ' + this.state.company; 
} 
render() { 
   return ( 
   <div> 
       <h1 style={{ 
       margin: 'auto', 
       width: '50%', 
       padding: 20, 
       marginTop: '10%', 
       border: 'solid 1px black', 
       textAlign: 'center', 
       fontSize: 18, 
       }}> 
       Best Online Training and Certifications : 
       {this.state.company} 
       <div id="warning"></div> 
       </h1> 
   </div> 
   ); 
} 
} 
export default App;

Step-4: RUN the code: 

npm start

As output, you will see the application changing the text in the heading every time the component gets updated. 

Example:2 Using componentDidUpdate() to increment a counter when the component becomes visible.

class ExampleComponent extends React.Component { 
   constructor(props)   
{ 
     super(props); 
     this.state = { 
       counter: 0, 
     };   
     this.incrementCounter = this.incrementCounter.bind(this); 
   } 
componentDidUpdate(prevProps, prevState) { 
     if (this.props.isVisible && !prevProps.isVisible) { 
       this.incrementCounter(); 
     } 
   } 
incrementCounter() { 
     this.setState((state) => ({ counter: state.counter + 1 })); 
   } 
render() { 
     return ( 
       <div>{this.state.counter}</div> 
     ); 
   } 
}

In the above example, the component update method sets the state based on props changes. The component's update method is invoked whenever the component's props or state changes. In this case, we are using it to increment a counter when the component becomes visible. 

 

Looking to enhance your coding skills? Join our Python Placement Course and unlock endless opportunities. Python, the versatile programming language, is in high demand across industries. Don't miss out on this chance to boost your career!

 

Conclusion

ComponentDidUpdate is part of the React component lifecycle. We use it to respond to external changes to a component's details or changes to its internal state. With componentDidUpdate, you can modify the central DOM node, request remote data, and update the internal state of your components. However, this must not be an end to expanding your knowledge in React.

Enhance your expertise with our comprehensive Software Engineering courses, designed to equip you with practical skills and knowledge to excel in the ever-evolving tech landscape.

Unlock your potential with our free Software Development courses, designed to equip you with the skills and knowledge needed to excel in the tech world. Start learning today and advance your career!

Frequently Asked Questions (FAQs)

1. What is the use of componentDidUpdate?

The componentDidUpdate() method allows us to run React code when the component is updated. Any network requests that must be made when the details are passed to the component change are coded here.

2. When should I use componentDidUpdate?

The DidUpdate component is useful when an activity should be performed after the DOM has been refreshed and the update line is vacant. This is generally helpful for complex delivery and state or DOM changes, or when you need to do some activity at the last.

3. What is componentDidUpdate in Hooks?

Each React part has a lifecycle, and one of them is componentDidUpdate.This lifecycle is when the React component state or prop value is updated. In class components, use the componentDidUpdate method to trigger side effects for the life cycle.

4. Why is componentDidUpdate not called?

The component will update() before rendering when a new detail or state is received. Use this as an opportunity to prepare before the update arrives.

5. What triggers componentDidUpdate?

The componentDidUpdate() hook triggers the action once we find an update in the component, but ensures that the hook method is not called when the part is first rendered. We can use the componentDidUpdate() hook in this way.

6. Is componentDidUpdate called after setState?

No! The componentDidUpdate is called only when all the components have already changed their states. You must call setState() quickly in componentDidUpdate() and make sure to enclose it by a condition, else it will create a boundless circle.

RELATED PROGRAMS