React V16.3 Before the lifecycle:
Before we talk about the React v16.3 life cycle update, let’s take a look at the old life cycle. Here’s the React life cycle:
A few points to note:
- ShouldComponentUpdate (props and State); shouldComponentUpdate (props and State);
- In the update several life cycle cannot use setState, (shouldComponentUpdate componentWillUpdate, render, componentDidUpdate) easy to cause an infinite loop, unless by some judgment to stop;
React V16.3 Lifecycle:
React V16.3 is not a major update to React, but it has a major life cycle change:
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
The deprecate has three life cycles (three with Will) :
- componentWillMount
- componentWillUpdate
- componentWillReceiveProps
Change the reason
The original (pre-React V16.0) life cycle became obsolete after React V16 introduced Fiber, as async rendering will be executed multiple times before render is enabled.
Ban cannot use effect is better than getting developers don’t use, so in addition to shouldComponentUpdate, other all functions before the render function (componentWillMount componentWillReceiveProps, ComponentWillUpdate) are replaced by getDerivedStateFromProps.
If you use three disabled life cycles after V16.3, you need to add UNSAFE__ in front of them, while in V17 you may be killed.
React V16.4 Lifecycle:
Life cycle overview diagram of 16.3 and 16.4:The projects. Wojtekmaj. Pl/react – lifec…
Compared to the previous version, getDerivedStateFromProps was modified to update the props, state changes, and forceUpdate to make the lifecycle easier to understand.
getDerivedStateFromProps
static getDerivedStateFromProps(props, state)
GetDerivedStateFromProps is called before the Render method is called, and is called both during the initial mount and during subsequent updates. It should return an object to update state, and if null is returned, nothing is updated.
We know that getDerivedStateFromProps is a static function in which the component instance is not accessible, which forces the developer to do no side effects before Render, but to decide on the new state based on the props and state, and that’s it.
getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState)
GetSnapshotBeforeUpdate () is called before the last render output (submitted to the DOM node). It enables the component to capture some information (for example, scroll position) from the DOM before changes are made. Any return values for this life cycle are passed as parameters to componentDidUpdate(prevProps, prevState, Snapshot).