Easy Tutorial
❮ React Refs React State ❯

React componentDidUpdate() Method

React Component Lifecycle

The componentDidUpdate() method is formatted as follows:

componentDidUpdate(prevProps, prevState, snapshot)

The componentDidUpdate() method is called immediately after an update occurs.

This method does not get called on the initial render.

You can also call setState() directly in componentDidUpdate(), but be aware that it must be wrapped in a condition.

The following example uses the componentDidUpdate() method to execute after the component updates. The component uses the componentDidMount() method to perform a modification operation after 1 second:

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritesite: "google"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "Updated favorite is " + this.state.favoritesite;
  }
  render() {
    return (
      <div>
      <h1>My favorite website is {this.state.favoritesite}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

React Component Lifecycle

❮ React Refs React State ❯