getSnapshotBeforeUpdate and componentDidUpdate

getSnapshotBeforeUpdate is called just before the DOM is updated. The value that is returned from getSnapshotBeforeUpdate is passed on to componentDidUpdate.

componentDidUpdate is called as soon as the DOM is updated. Resizing the window during rendering is an example of when getSnapshotBeforeUpdate can be useful.

Let's have a look at these life cycle methods in our app:

  1. Let's add the following near the top of the App class, under the timer variable declaration:
private renderCount = 0;
  1. Now, let's add the life cycle methods:
public getSnapshotBeforeUpdate(prevProps: {}, prevState: IState) {
this.renderCount += 1;
console.log("getSnapshotBeforeUpdate", prevProps, prevState, {
renderCount: this.renderCount
});
return this.renderCount;
}

public componentDidUpdate(prevProps: {}, prevState: IState, snapshot: number) {
console.log("componentDidUpdate", prevProps, prevState,
snapshot, {
renderCount: this.renderCount
});
}

Look at the running app:

We see the methods being invoked in the order we expect, and componentDidUpdate successfully taking in the render count from getSnapshotBeforeUpdate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.71.237