DEV Community

Discussion on: Shallow comparison in Redux

Collapse
 
misterwhat profile image
Jonas Winzen

Hey :)
great article. It is really clarifying why immutability is so important when writing reducers for state management.

I hope you don't mind if I correct you in one point:

In Redux, a reducer is a function which does a certain job (it changes the app's state ).

This is only partially correct. A reducer should never change the state of an app (thats mutation), but rather create the next state of an app, given an action + the last state.

To make sure reducers are not mutating existing state you could Object.freeze() your data structures that you use for your reducer unit tests. (keep in mind that Object.freeze() only shallow freezes an object. So you would need to recurse (see example) over nested structures, to completely protect them from mutations).
_Object.freeze() slows down property access, so don't use it in production 😉

Based on my past experience on using Redux for state management, I found it quite more comfortable to use Ramda for writing reducer logic, rather than Immutable.js.
While Immutable.js is a sophisticated and super fast library to work with immutable data, it is not very compatible with existing components and pieces of an App (assuming you are not starting entirely from scratch and never plan to use any existing library - ever).
As soon as you are in the need for plain old JS data, you might be tempted to star using the .toJS() functions of your immutable collections, to make it consumable for other APIs. .toJS() is quite slow and outperforms the benefits you have from using Immutable.js.
A compatible approach to building rock solid, composable reducer logic is to use Ramda (using lenses to combine selector and reducer logic in a directly composable format).

Collapse
 
machy44 profile image
machy44 • Edited

Sorry for the delayed answer. Yeah, you are right reducer create a new state. I had chosen the wrong words.
I have never used Immutable.js and Rambda so far. Thank you for giving me a lot of excellent information in your comment.