Loading

getSnapshotBeforeUpdate() example in React

getSnapshotBeforeUpdate() example in React

Today, we will see an example of getSnapshotBeforeUpdate() in React. In React documentation, it has been said that it is rarely used life cycle method for the class component. It is invoked right before every component update. By using this life cycle method we can log the scroll position or any other dom element position before every dom update. Let's take an example of a button position before a component update.

Create a paragraph and a button. On button onClick event we will show/hide the paragraph.

On the constructor method take a state variable and set it to true.

constructor() {
    this.state = {
        showHidePara: true
    }
}

On the render(), create the paragraph and button.

{this.state.showHidePara ? <div>We can see the paragraph</div> : null}
<button
    onClick={() => this.setState({showHidePara: !this.state.showHidePara})}
>
    {this.state.showHidePara ? Hide Paragraph : Show Paragraph}
</button>

Up to this point if we run our application we will see "We can see the paragraph" on page load. Now, if we click the button again and again the paragraph will show/hide.

You may also like: React - Basic Form building and validation with Formik and Yup

Let's come to the next point. To get the button position we need to create Ref using React.createRef() under the constructor method.

this.btnRef = React.createRef();

And attach the Ref with the Show/Hide button.

{this.state.showHidePara ? <div>We can see the paragraph</div> : null}
<button
    onClick={() => this.setState({showHidePara: !this.state.showHidePara})}
    ref={this.btnRef}
>
    {this.state.showHidePara ? Hide Paragraph : Show Paragraph}
</button>

You may also like: How to update the state based on the previous state

Next, create the getSnapshotBeforeUpdate() and componentDidUpdate(). On the third parameter we can catch the snapshot returned from the getSnapshotBeforeUpdate(). The offsetTop return the positon of the button.

getSnapshotBeforeUpdate(prevProps, prevState) {
    const btn = this.btnRef.current;
    return btn.offsetTop || null;
}

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('Snapshot', snapshot);
}

Finally, run the application and open the console. You can see the updated button position on every updated render.

Related Articles