ScanSkill

getSnapshotBeforeUpdate()

The getSnapshotBeforeUpdate() method gives access to the props and state of the component before the update. That means even after the component's update, we can get its previous value of the state and props. We must include the componentDidUpdate() method while using getSnapshotBeforeUpdate().

Syntax

getSnapshotBeforeUpdate(prevProps, prevState) {
     // function here
  }

Example

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "John" };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({ name: "Billy" });
    }, 1000);
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("The previous value was : ", prevState.name);
  }
  componentDidUpdate() {
    console.log("The updated value is : " + this.state.name);
  }
  render() {
    return (
      <div>
        <h1>My name is {this.state.name}</h1>
      </div>
    );
  }
}

Example

getSnapshotBeforeUpdate

Here, the state name's initial value is "John" which is updated after the component is rendered to the new value "Billy". So, the previous value is "John" which is accessed inside getSnapshotBeforeUpdate().