Today I Learned

hashrocket A Hashrocket project

Return value of snapshot in componentDidUpdate

React has a rarely used lifecycle method getSnapshotBeforeUpdate where you get the opportunity to look at your current DOM right before it changes.

The return value of this method is the third parameter of componentDidUpdate.

getSnapshotBeforeUpdate(prevProps, prevState) {
	return "value from snapshot";
}

componentDidUpdate(prevProps, prevState, snapshotValue) {
  console.log(snapshotValue);
}

The above code will output value from snapshot in the log.

The purpose for getSnapshotBeforeUpdate given in the React documentation is for making sure a value that can't be set with rendering - like the scroll position - is exactly where you want it based on the state it was before the rerender.

My code example is here.

See More #react TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.