Let’s start with a question: when a component changes (state, property, or otherwise), does its child component rerender?
Solution: There are three cases
When the props of a component changes
A component is like a function that takes props and returns a new component to update the UI, so the render function is called when the properties of the parent component change
When the state of the component changes
State is similar to props, except that state is controlled internally by the component, and when state is updated, render is triggered to update the UI
When there are other changes to the component
Const Text = () => {const handleClick = () => {console.log(' click '); } the return (< div > < div onClick = {() = > handleClick} > click < / div > < TextOne / > < / div >)}Copy the code
In this case, the Update to the TextOne component is not triggered because the changes to state and props are not triggered
The next question is: is the render function called every time the parent component’s props or state changes, so the child component is also recreated?
According to the documentation, render just generates a new tree to compare with the old tree. In the process of comparison, diff algorithm is used
In the diff algorithm, when the root of an element changes, such as from to
, the component is unloaded and recreated.
If diff detects that the element has not changed, but the attribute has changed, the component instance is not unloaded, only updated
So now it is clear that when the state of the parent component changes, the child component will also be rerendered, and a new tree will be generated at render time, and the diff algorithm will be used to decide whether to update
React does the diff algorithm, but render has a performance cost every time. So the next direction is how do you reduce the number of render times for child components
React provides several methods for controlling render. PureComponent/shouldComponentUpdate /useMemo When using these methods, you can use PreProps or PreState to decide when to render