getSnapshotBeforeUpdate() in ReactJS

getSnapshotBeforeUpdate(prevProps, prevState) is invoked after render() method but just before DOM is changed.

So, getSnapshotBeforeUpdate() is called before the rendered output ( given by render() ). That means before virtual DOM is converted to actual DOM ( known as pre-commit phase ), this method is called.

getSnapshotBeforeUpdate(prevProps, prevState) has recently updated props and state as parameters. The value you return in getSnapshotBeforeUpdate() is available in componentDidUpdate() as the third parameter.

Why getSnapshotBeforeUpdate() should be used?

getSnapshotBeforeUpdate() is used very rare when you need to get some information from DOM before DOM is changed.

Let us have a look at an example.


import React from 'react';
import ReactDOM from 'react-dom';

class ChatLists extends React.Component{
    constructor(props){
        super(props);
        this.chatListRef = React.createRef();
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        // Check if new item is added in chatList or not.
        // If anything is added to the chatList, then return the difference between
        // scrollHeight and scrollTop.
        if (prevProps.chatList.length < this.props.chatList.length) {
            const chatList = this.chatListRef.current;
            return chatList.scrollHeight - chatList.scrollTop;
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        // If any value is returned from getSnapshotBeforeUpdate method, it will be 
        // available as 3rd parameter snapshot. If it is available, adjust the 
        // scrollTop of chatList.
        if (snapshot) {
            const chatList = this.chatListRef.current;
            chatList.scrollTop = chatList.scrollHeight - snapshot;
        }
    }

    render() {
        return (
            
{ /***** Render chat list ********/ }
); } }

Points to remember while using getSnapshotBeforeUpdate()

There are many points that you should remember while using getSnapshotBeforeUpdate() method.

  • Sometimes, there is some delay between render ( render phase ) and componentDidUpdate. If some props changes in that delay and you want to get some data from DOM, you can use getSnapshotBeforeUpdate.
  • Any value or null should be returned by getSnapshotBeforeUpdate() method.

Conclusion

In this section, we learned about getSnapshotBeforeUpdate() method and for what it can be used.
In the next section, you will learn about componentDidUpdate() method of ReactJS component.