0

I am learning to react lifecycle methods but stuck at a query and not able to find the answer even after lots of research over the web.

As per the react official documentation here, it is said that the method getSnapshotBeforeUpdate is used to perform something just before the DOM commit. The snapshot returned by this function will be later used by componentDidUpdate.

The query: The parameters 'prevProps' and 'prevState' are already present in method componentDidUpdate, then why does it need the help of function getSnapshotBeforeUpdate? I mean the function componentDidUpdate has necessary inputs to perform what getSnapshotBeforeUpdate is doing.

Any help would be appreciated.

Best, Rahul

Rahul Agarwal
  • 41
  • 1
  • 7

1 Answers1

4

As clearly mentioned in the documentation with an example, the purpose of getSnapshotBeforeUpdate method is not to just get information from prevProps and/or prevState.

But it can be used to extract some information from the previous DOM (such as the current scroll position of a div) before the DOM is updated. Most cases, such DOM related values may not be covered by the prevProps or prevState.

When you consider only the componentDidUpdate method, the DOM has already updated (hence the name DidUpdate) when it's been called. So all the information related to the previous DOM has lost by that time.

Therefore the extracted information on previous DOM from getSnapshotBeforeUpdate can be passed to the componentDidUpdate method to use it there.

Udith Gunaratna
  • 2,091
  • 1
  • 13
  • 17