The componentDidUpdate() method allows us to execute the React code when the component is updated. All the network requests that are to be made when the props passed to the component changes are coded here.
The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes.
Syntax:
componentDidUpdate(prevProps, prevState, snapshot)
Parameters: Following are the parameter used in this function:
- prevProps: Previous props passed to the component
- prevState: Previous state of the component
- snapshot: Value returned by getSnapshotBeforeUpdate() method
Tip: To avoid an infinite loop, all the network requests are needed to be inside a conditional statement as:
componentDidUpdate(prevProps, prevState) {
if (prevState.data !== this.state.data) {
// Now fetch the new data here.
}
}
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.

Project Structure
Example: In this example, we are going to build a React application that changes the text in the heading when the state of the component is updated.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';
class App extends React.Component {
state = {
company: 'GFG'
};
componentDidMount() {
setTimeout(() => {
this.setState({ company: 'GeeksForGeeks' });
}, 600);
}
componentDidUpdate() {
document.getElementById('disclaimer').innerHTML =
'P.s: GFG 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,
}}>
Greatest Science Portal For Geeks :
{this.state.company}
<div id="disclaimer"></div>
</h1>
</div>
);
}
}
export default App;
|
Note: You can apply your own styling to the application.
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:

Output
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
31 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...