Reputation: 55729
Dan Abramov says
...a component is pure if it is guaranteed to return the same result given the same props and state.
So if a component is supplied with the same props the same output will always be returned. This is clear.
He then says
pure components... don’t rely on deep mutations in props or state, so their rendering performance can be optimized by a shallow comparison in their
shouldComponentUpdate()
hook
But this means I could supply a pure component with the same props object, but with a difference located deeper inside said props object, and the component would render the same but for different (albeit a deep difference) props. This means this constraint is not enforced.
Is declaring a component as extends PureComponent
really saying to ReactJS "I know what I am doing. I guarantee I am using immutable state. So you need only perform shallow props comparisons in shouldComponentUpdate
"?
Finally, PureComponent
s provide a shallow shouldComponentUpdate
method by default - presumably this can be overridden with whatever you want (even a deep comparison)?
Upvotes: 4
Views: 339
Reputation: 11
https://medium.com/groww-engineering/stateless-component-vs-pure-component-d2af88a1200b
class Welcome extends React.PureComponent {
render() {
return <h1>Welcome</h1>
}
}
Hello = () => {
return <h1>Hello</h1>;
}
So above there is an example of a very simple Welcome Pure Component and Hello Stateless Component. When you use these two in your Parent Component, you will see Hello will re-render whenever Parent Component will re-render but Welcome Component will not
Also in cases where you want to use lifecycle methods of Component then we have to use Pure Components as stateless components don't have lifecycle methods.
Upvotes: 1
Reputation: 11176
Please read about Pure Render Checks https://github.com/vasanthk/react-bits/blob/master/gotchas/01.pure-render-checks.md
and good articles there :
https://flexport.engineering/optimizing-react-rendering-part-1-9634469dca02 https://flexport.engineering/optimizing-react-rendering-part-2-7b2e9a9ea21f https://flexport.engineering/ending-the-debate-on-inline-functions-in-react-8c03fabd144
Upvotes: 0
Reputation: 22352
Is declaring a component as extends PureComponent really saying to ReactJS "I know what I am doing. I guarantee I am using immutable state. So you need only perform shallow props comparisons in shouldComponentUpdate"?
Yes
Finally, PureComponents provide a shallow shouldComponentUpdate method by default - presumably this can be overridden with whatever you want (even a deep comparison)?
You can override it. React will try to warn you not to do so. In this case its better to inherit from Component
instead.
Upvotes: 1