ReactJS – getSnapshotBeforeUpdate() Method

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to execute a function after the component is updated and before rendering it to the DOM.

This method is called before the rendering of the component and after it is updated. This method is majorly used to compare the previous state or the previous props of the component with the new state or the new received props. The value returned by this method is passed as an argument to the componentDidUpdate method.

Syntax

getSnapshotBeforeUpdate(prevProps, prevState)

Parameters

  • prevProps − Previous props passed to component

  • prevState − Previous state of component

Example

In this example, we will build a React application which fetches the list of users and on clicking the fetch user button the Show component will get placed in the DOM and after updating this component getSnapshotBeforeUpdate method is called which displays the previous value of the state.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         show: false,
      };
   }
   render() {
      return (
         <div>
            <h1>User List</h1>
            <h3>Username: Rahul</h3>
            <button onClick={() => this.setState({ show: true })}>
               Fetch Users
            </button>
            {this.state.show ? <User email="new@gmail.com" /> : null}
         </div>
      );
   }
}
class User extends React.Component {
   constructor() {
      super();
      this.state = {
         email: 'previous@gmail.com',
      };
   }
   componentDidMount() {
      this.setState({ email: this.props.email });
   }
   getSnapshotBeforeUpdate(prevProps, prevState) {
      // Displaying the previous state
      document.getElementById('previous').innerHTML = 'Previous Name: ' + prevState.email;
   }
   componentDidUpdate() {
      // Displaying the current state
      document.getElementById('new').innerHTML = 'Current Name: ' + this.state.email;
   }
   render() {
      return (
         <div>
            <div id="previous">Previous Email: </div>
            <div id="new">New Email: </div>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

raja
Published on 18-Mar-2021 11:58:14
Advertisements