Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does react setState execute if the old and new value are the same?

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?

like image 786
Pho Huynh Avatar asked Oct 19 '17 07:10

Pho Huynh


1 Answers

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.


Extending with 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.


Manually checking on 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.

like image 96
Chris Avatar answered Oct 04 '22 17:10

Chris