The most unknown redux performance trick
Regarding optimizing redux, there are some well known techniques: memoizing, using reselect for example.
But there is one that remains unknown to many, although it’s simple and very efficient: The connect’s areStatesEqual option.
When state changes, all connect functions will be called, props mapped from state and component rendered. Imagine something like this :
Considering action addTodo adds a todo item in the todo reducer, when this action will be called, both connect will then be called and mapStateToProps computed.
Using areStatesEqual option, you can tell when not to bother to call mapStateToProps at all.
The docs say :
areStatesEqual] (Function): When pure, compares incoming store state to its previous value. Default value:
It’s fairly simple. This function is passed 2 arguments: the next state, and the previous state. You return a boolean telling whether the two states have changed, regarding the state slice you’re interested in, and if the function returns true, mapStateToProps will not even be called.
Let’s update our example to use this function :
Now, when state.users.all changes, the TodoContainer’s areStatesEqual option will be called, it will return true, and thus it’s mapStateToProps function won’t even be called.
If you have a more complex selector, simply compare each part of the state used in mapStateToProps:
Most of the times it is enough and I rarely use memoization.
These examples don’t have complex computation of props, so in these cases performance wouldn’t be impacted so much since by default connected components are pure. They’re just examples. It makes much more sense when using more complex mapStateToProps.
Memoization remains useful when using props in mapStateToProps and methods that return new objects or arrays.
Perfs gain can be really impressive only using this simple trick.