Understanding React — React 16.3 + Component life-cycle

The release of 16.3 introduced some new life-cycle functions, which replace existing ones to provide better support for the new asynchronous nature of React.

This article is an update on the previous one, which talked about the “old” lifecycle, thus it’s not going to focus on all of the lifecycles, only the new ones.

static getDerivedStateFromProps(nextProps, prevState)

The new function which main responsibility is ensuring that the state and props are in sync for when it is required. It’s main job is replacing componentWillReceiveProps

gDSFP is a static function and as such has no access to this — you are instead expected to return an object, which will be merged into the future state of the component (exactly like working with setState!)

The function is used when a component is updated but also when it is mounted, right after the constructor was called, so you no longer need to use constructor or class property form of state if you want to set initial state from props.

getSnapshotBeforeUpdate(prevProps, prevState)

Other of the two new functions, invoked in the so called “pre-commit phase”, right before the changes from VDOM are to be reflected in the DOM.

It is usable mostly if you need to read the current DOM state, for example you have an application in which new messages are added to the top of the screen — if a user scrolled down, and a new message is added the screen could move and make the UI harder to use. By adding getSnapshotBeforeUpdate you can calculate current scroll position and maintain it through the DOM update.

Even though the function is not static, it is recommended to return the value, not update the component. The returned value will be passed to componentDidUpdate as the 3rd parameter.

Deprecated functions

While the new functions are there to make your transition to AsyncMode easier, you are not forced to migrate all your code. The following functions will be marked as deprecated and in later releases renamed:

  • componentWillReceiveProps — UNSAFE_componentWillReceiveProps
  • componentWillUpdate — UNSAFE_componentWillUpdate

You will start seeing the deprecation warnings in next major version, and the function will be removed (the renamed versions will be kept!) in version 17.0

Dan Abramov summarized the whole change in one image for your pleasure:

Summary of the new life-cycle