Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React redux connect rendering optimisation

I am trying to get how to manage complex state in React, with limiting the number of render calls for components whose content has not changed.

As example:

I have simple connected to redux store container component with "items" props (which is array).

const Component = ({ items }) => (
    <>{items.map(item => <ItemComponent key={item.id} {...item} />}</>
);

const mapStateToProps = state => ({
    items: $$data.select.items(state),
});

const ConnectedComponent = connect(mapStateToProps)(MyComponent);

Every time any part of the complex store changes – the items prop changes also, even if items data didn't update, even if it is empty: oldProp: [] => newProp: []. And it causes rerendering. (I found it in React Dev Tools, it highlights updated components)

Should I worry about this unnecessary rerenders? What is the best way to deal with it? I already found that new React.memo hoc stops rerenderings, but is it good way ?

like image 678
Max Vorozhcov Avatar asked Dec 10 '22 02:12

Max Vorozhcov


1 Answers

The use of mapStateToProps in your connect() call means you want your component to be notified when the store changes - this will happen regardless of whether the small fragment you are interested in has changed or not. Further to this, react-redux prevents unnecessary re-renders itself by performing a shallow comparison on the object returned by mapStateToProps and the previous props.

Looking at your example, scenarios like this newProp: [] would create a new array each time therefore would fail a shallow comparison because the arrays are different instances.

Should I worry about this unnecessary rerenders?

React takes care not re-rendering components unnecessarily, so even if render is called again, as long as the props to said component haven't actually changed then React won't do any additional work. It's probably safe to say that, for the majority of applications, unnecessary re-renders aren't all that much of a concern.

If you feel it will affect your application or you just want to know more about ways to reduce it then there are plenty of material on the subject of performance:

  • React-Redux - mapStateToProps and Performance
  • React - Optimizing Performance
like image 135
James Avatar answered Dec 19 '22 16:12

James