Easy Tutorial
❮ React Lists And Keys Home ❯

React getSnapshotBeforeUpdate() Method

React Component Lifecycle

The format of the getSnapshotBeforeUpdate() method is as follows:

getSnapshotBeforeUpdate(prevProps, prevState)

The getSnapshotBeforeUpdate() method is invoked right before the most recent render output (committed to the DOM nodes).

Within the getSnapshotBeforeUpdate() method, we can access the previous props and state.

The getSnapshotBeforeUpdate() method needs to be used in conjunction with the componentDidUpdate() method, otherwise an error will occur.

The following example uses the getSnapshotBeforeUpdate() method to view the value of the state object before the update. The example will display the difference between the values before and after the update after a 1-second delay:

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritesite: "google"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "The favorite site before the update was: " + prevState.favoritesite;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The favorite site after the update is: " + this.state.favoritesite;
  }
  render() {
    return (
      <div>
        <h1>My favorite site is {this.state.favoritesite}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

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

React Component Lifecycle

❮ React Lists And Keys Home ❯