Initial state:
this.state = {
someVar: true
};
What if I have a code that set state value the same as the old one:
this.setState({
someVar: true
});
Does the second snippet execute? And does it cost the performance if it does execute and run many times?
Does the second snippet execute? And does it cost the performance if it does execute and run many times?
Yes and yes. However, there are two approaches to preventing this from happening.
PureComponent
Normally when writing a React Component you would write:
class MyComponent extends React.Component {
If you want React to perform a shallow comparison on the new and old props and state, you would write instead:
class MyComponent extends React.PureComponent {
This is the simpler approach. More info from the official documentation, here.
shouldComponentUpdate()
You can always perform this logic yourself and tell React when to ignore a re-render with the shouldComponentUpdate()
lifecycle method.
shouldComponentUpdate(nextProps, nextState) {
if(this.state.someVar === nextState.someVar) return false;
return true;
}
In the above example, the component will not re-render if someVar
is the same across renders. However, any other update to another state or prop variable will trigger a re-render.
More info from the official documentation, here.
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