componentDidUpdate()
is one of many lifecycle methods that are part of the React Component API.
componentDidUpdate()
is invoked immediately after a component is updated. However, this method is not called for the initial render.
You can use the componentDidUpdate()
method as an opportunity to operate on the DOM when the component has been updated. The method can be used to make network requests, for example.
Make sure you are already familiar with React Components and Lifecycle.
componentDidUpdate(prevProps, prevState, snapshot)
prevProps
: previous props before the updateprevState
: previous state before the updatesnapshot
: component snapshot, but only if the component implements the getSnapshotBeforeUpdate()
(which is rare), otherwise undefinedNote:
componentDidUpdate()
will not be invoked ifshouldComponentUpdate()
returns false.
Let’s consider a real-world scenario where componentDidUpdate()
is useful.
Suppose you are implementing an autosave feature. After a user inputs something, we want to save the input by uploading it via Ajax.
Upon entering, user input changes the component state or, in other words, the component is updated, so, we can make the Ajax request using componentDidUpdate()
.
Whenever the user enters something, changeName()
is called and the component’s state is updated. componentDidUpdate()
is then invoked immediately after the component update.
import React from 'react'; import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
Note: You may immediately call
setState()
incomponentDidUpdate()
, but it must be wrapped in a condition (like in the example shown above) or you’ll cause an infinite loop.
Free Resources