Namit
Namit

Reputation: 31

In what cases does the setState() NOT cause a re-render in a React Component?

I know that usually any change in the props or the state of a React Component causes it to re-render, but what are the scenarios when a setState() call can be made and not cause a re-render?

Upvotes: 3

Views: 7205

Answers (1)

Matt
Matt

Reputation: 511

When inheriting from plain React.Component React will by default call render() on the component when either the parent component re-renders or setState is called in the component.

However, if you implement shouldComponentUpdate() in your React component you will be able to short-circuit the update cycle. This is useful if you only have a limited number of props that are primitive values (string, number, bool) or when working with immutable data structures. Then you can simply do something like this:

shouldComponentUpdate(nextProps, nextState) {
  return nextState.name !== this.state.name // Don't re-render if name is equal
}

The default implementation of shouldComponentUpdate() is

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

It is also possible to inherit from React.PureComponent which basically implements shallow comparison of your props and state.

I would recommend the following articles for a more in-depth answer: https://reactjs.org/docs/optimizing-performance.html#avoid-reconciliation and https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578 (Especially the section called (PureComponent and shouldComponentUpdate)

It is also useful to understand the difference between what happens when the render-function is called and what the reconciliation algorithm does to update the DOM. More on this here.

Upvotes: 5

Related Questions