Method 2: getSnapshotBeforeUpdate

Let's discuss the "getSnapshotBeforeUpdate" method which stores the previous version of the application before uploading the changes.

In the updating component phase, the getSnapshotBeforeUpdate lifecycle method is called right after the render method.

Understanding the Mechanism

This one is a little tricky, but I’ll take my time explaining how it works.

Chances are you won’t always reach for this lifecycle method, but it may come in handy in certain cases. Specifically, when you need to grab some information from the DOM (and potentially change it) just after an update is made.

Here’s the important thing. The value queried from the DOM in getSnapshotBeforeUpdate will refer to the value just before the DOM is updated, even though the render method was previously called.

An analogy that may help has to do with how you use version control systems such as git.

A basic example is that you write code and stage your changes before pushing to the repo.

In this case, assume the render function was called to stage your changes before actually pushing to the DOM. Before the actual DOM update, information retrieved from getSnapshotBeforeUpdate refers to those before the actual visual DOM update.

Actual updates to the DOM may be asynchronous, but the getSnapshotBeforeUpdate lifecycle method will always be called immediately before the DOM is updated.

Example: Chat Panel

Don’t worry if you don’t get it yet. I have another example for you.

Get hands-on with 1200+ tech skills courses.