Pho Huynh
Pho Huynh

Reputation: 1577

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?

Upvotes: 13

Views: 9586

Answers (4)

Chris
Chris

Reputation: 59511

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.

Upvotes: 11

Andy Theos
Andy Theos

Reputation: 3346

Actually you can call multiple setStates and React may batch multiple setState() calls into a single update for performance. But keep in mind that this will be async (setState updates doc).

As for setting the same state, all other answers are correct. SetState will execute even when new value is equal.

Upvotes: 0

Sulthan
Sulthan

Reputation: 130102

Setting state will only set new values, there is no comparison with the previous state. shouldComponentUpdate is then invoked to decide whether render should take place or not.

Note that it returns true by default.

Upvotes: 0

Daniel Andrei
Daniel Andrei

Reputation: 2684

Yes, it does if you don't have any comparison regarding state in your shouldComponentUpdate.

You can do this by default if your component extends PureComponent instead. You can read more here.

Upvotes: 1

Related Questions