I am trying to create a component that shouldn't when a certain property is true, but should perform a shallow compare (the default for PureComponent
).
I've tried doing the following behavior:
export default class ContentsListView extends PureComponent<Props> {
shouldComponentUpdate(props: Props) {
if (props.selecting) {
return false;
}
return super.shouldComponentUpdate(props);
}
render() {
}
}
However, super.shouldComponentUpdate
is not defined. Is there some way to "tap into" the shallow compare of PureComponent
without writing my own?
PureComponent implements shouldComponentUpdate() method to determine re-rendering with a shallow prop and state comparison for rendering performance optimization. Although overridden shouldComponentUpdate() method will work as intended, it is recommended to extend React.
What does “shouldComponentUpdate” do and why is it important ? The shouldComponentUpdate is a lifecycle method in React. This method makes the component to re-render only when there is a change in state or props of a component and that change will affect the output.
The shouldComponentUpdate method is majorly used for optimizing the performance and to increase the responsiveness of the website but do not rely on it to prevent rendering as it may lead to bugs.
The difference between them is that React.Component doesn't implement shouldComponentUpdate() , but React.PureComponent implements it with a shallow prop and state comparison.
There is no super.shouldComponentUpdate
in PureComponent
because it implements shallow checks by checking isPureReactComponent
property, not with shouldComponentUpdate
. A warning is issued when both isPureReactComponent
and shouldComponentUpdate
are in use because shouldComponentUpdate
efficiently overrides the behaviour of isPureReactComponent
.
React doesn't expose its shallowEqual
implementation, third-party implementation should be used.
In case this becomes a common task, own PureComponent
implementation can be used for extension:
import shallowequal from 'shallowequal';
class MyPureComponent extends Component {
shouldComponentUpdate(props, state) {
if (arguments.length < 2)
throw new Error('Do not mess super arguments up');
return !shallowequal(props, this.props) || !shallowequal(state, this.state);
}
}
class Foo extends MyPureComponent {
shouldComponentUpdate(props, state) {
if (props.selecting) {
return false;
}
return super.shouldComponentUpdate(props, state);
}
}
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