 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ReactJS – getSnapshotBeforeUpdate() Method
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.

