ReactJS componentDidUpdate() Method
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.
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 { // Defining the state state = { company: 'GFG' }; componentDidMount() { // Changing the state after 600ms setTimeout(() => { this .setState({ company: 'w3wiki' }); }, 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 Beginner : { 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: