5

I just started to studying React.

When learning LifeCycle and I wonder about componentDidUpdate method.

As I read componentDidUpdate method can have three params (prevProps, prevState, snapshot). If I can find out prevState from componentDidUpdate what is the snapshot for?

It may not important but I just got curious

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
EUNJI JO
  • 63
  • 5

1 Answers1

3

From the componentDidUpdate docs:

If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate(). Otherwise this parameter will be undefined.

getSnapshotBeforeUpdate

getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate().

This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way.

A snapshot value (or null) should be returned.

Use-cases appear mostly related to querying the DOM, or anything that can't be derived from state or props.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thanks for this. I also thought what the importance of snapshots are, but your explanation on "things that cannot be derived from `state` or `props` makes so much sense. – Dillion Jan 25 '23 at 23:01
  • Can you please provide an example of `getSnapshotBeforeUpdate()` with real use cases? Right now answer is not clear enough. @Drew Reese – wayne Jul 11 '23 at 07:43
  • @wayne Do you need something more than what is provided as an example in the official docs the answer links to? – Drew Reese Jul 18 '23 at 07:08
  • I need some common use cases we can come across. @DrewReese – wayne Jul 18 '23 at 07:19
  • 1
    @wayne Instead of me dreaming up arbitrary examples that you may or may not find helpful it sort of sounds like you might have a specific issue that you are trying to use `getSnapshotBeforeUpdate` for and it might just be more beneficial for you to create a new SO post with details specific to your issue. If you do create a post feel free to ping me here in another comment with a link to it and I can take a look when available. – Drew Reese Jul 18 '23 at 07:47