Having read the official React documentation, I've came across this regarding PureComponent:
Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.
Why exactly does skipping props updates for the whole subtree means avoiding non-pure components? what would be the consequences of a non-pure component inside a PureComponent's component subtree (both in general and in the case when it's not designed/supposed to respond to props change).
A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.
PureComponent Is Primarily Used for Performance Optimization. As outlined in the React docs: If your React component's render() function renders the same result given the same props and state, you can use React.
Rule of thumb: A component should be made pure if its render causes a performance issue and the render can be prevented by making the component pure.
To sum it up, PureComponent is useful when: You want to avoid re-rendering cycles of your component when its props and state are not changed, and. The state and props of your component are immutable, and. You don't plan to implement your own shouldComponentUpdate lifecycle method.
A Pure Component for the same set of input props will give absolutely the same result, not just for itself but for the entire DOM tree. When you declare a PureComponent
, not only do you need to think about props and state
, but also context
. PureComponents
Block any context changes. Consider an example
<MyApp>
<Router> // react-router.
<App> // A PureComponent
<Switch> // react-router Switch
<Route ....>
</Switch>
</App>
</Router>
</MyApp>
React-router’s Router will store current location in router props of context. And React-router’s Switch will read it back and choose a Route.But since App
is a very pure component, and will not react to context
change in Router, because it not using
that values and should ignore them. And hence when you have a PureComponent in place, you should think about not only the component but also its nested children. So essentially you would also keep all your children Pure.
Each prop should be immutable. It needs to easier debug. For example. You put array of users via props. But, one of components do: user.name = value. Children components may be much, and you will difficult understand, what is component updates the user?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With