Reading guide
In this paper, the overall structure of the total score is adopted. First, the React lifecycle flow chart is presented to let everyone know what our research objectives are. In the second part, the key and difficult life hook functions in the React lifecycle are introduced. The third part gives a summary of the React lifecycle.
React Lifecycle flowchart
1. getDerivedStateFromProps(props, state)
Calling this hook function makes the state value at any time dependent on props.
This function is static, so we add static.
What is returned?
It should return a status object (or null), but it should return an object and a warning if you return nothing. The returned object is the state that Render will render
What is it receiving?
Accepts two parameters, the latest props and the latest state.
CodeSandBox online demo
2. shouldComponentUpdate(nextProps, nextState)
What is it receiving?
Accepts two parameters, one is the latest props, which is not yet render, and the other is the latest state, which is not yet render.
What is returned?
Returns a Boolean value, true to update the current component, false to not update the current component.
CodeSandBox online demo
3. componentDidMount
What was accepted?
This lifecycle hook function is called at the end of the mount and takes no arguments.
In this hook function, you can handle some of the operations after the component is mounted.
4. getSnapshotBeforeUpdate(preProps,preState)
What is it receiving?
Accepts two parameters, one for the props before and one for the state before.
What is returned?
In this lifecycle hook function, some HTML properties are recorded before the DOM is updated, and the value returned is received by the third parameter to componentDidUpdate.
CodeSandBox Live Demo (News scrollbar case)
5. componentDidUpdate(prevProps, prevState, snapshot)
What is it receiving?
It receives the props before and the state before, which is lagging with the DOM, and the third argument is received from getSnapshotBeforeUpdate.
What is returned?
Nothing is returned, but you can do an updated comparison here, manipulate the DOM, or make a network request.
6. componentWillUnmount()
This lifecycle function is called before the component is uninstalled, where you can do things like clear timers. SetState should not be called in this lifecycle hook function because the component will never be rerendered.
7. forceUpdate(callback)
This lifecycle function can update components without changing state or props, call Render, and shouldComponentUpdate without passing the hook shouldComponentUpdate.
CodeSandBox online demo
Summary life cycle
The most important thing to remember about the React lifecycle is what does each lifecycle hook function receive? What is returned? At what stage call, this is the core is also the key, finally must memorize the flow chart!