Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will React trigger state update if new provided value is the same? [duplicate]

Does React component do some checking on it's state once this.setState() is called to see if the state has changed. So there will be no reconciliation phase one again after componentDidMount was called like in the code below:

// in constructor
this.state = {width: 0}
...
// in componentDidMount method
this.setState(() => ({ width: 0 }))

or I need to do those checks manually, like:

const width = getViewportWidth()
if (this.state.width !== width) {
  this.setState(() => ({
    width
  }))
like image 769
zmii Avatar asked Dec 04 '25 14:12

zmii


2 Answers

By default, React will re-render everytime a component gets passed props or state.

You can do some checking in shouldComponentUpdate and then decide whether to re-render or not.

From the docs:

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Currently, if shouldComponentUpdate() returns false, then componentWillUpdate(), render(), and componentDidUpdate() will not be invoked.

Returning false does not prevent child components from re-rendering when their state changes.

TLDR; Returning false in shouldComponentUpdate will prevent re-rendering, except when the state actually changed.

like image 111
Jackyef Avatar answered Dec 07 '25 03:12

Jackyef


setState doesn't compare the previous and current state value, it just set its and a reconcilation is done again.

CodeSandbox that simulates this behaviour

What you can do it implement the shouldComponentUpdate method

Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.

shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

Returning false does not prevent child components from re-rendering when their state changes.

What you would do is

shouldComponentUpdate(nextProps, nextState) {
     if(this.state.width === nextState.width) {
          return false
     }
     return true;
}
like image 44
Shubham Khatri Avatar answered Dec 07 '25 04:12

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!