DEV Community

DaCastle
DaCastle

Posted on

Immer or Immutable for Redux Reducers?

What I was trying to achieve were cleaner, more intuitive Redux reducer files for my application. I noticed there was a ton of bloat with having to worry about not mutating the current state of the store or state objects before updating it. It gets ugly fast:

case USER_CLICKED_CHECKOUT:
return {
    ...state,
    checkoutCart : {
        ...state.checkoutCart,
        isCheckingOut : true
    }
}
Enter fullscreen mode Exit fullscreen mode

And that's to update a single variable. 1 line for the case, 2 for the return block, 4 for preventing mutations, and 1 for the value update.

With Immer, this turns into:

case USER_CLICKED_CHECKOUT
draft.checkoutCart.isCheckingOut = true
return
Enter fullscreen mode Exit fullscreen mode

1 line for the case, 1 for the return, and 1 for the value update.
That's much cleaner AND more apparent what the desired intent is.

From the resources I've looked into so far, in regards to Redux Reducers, Immer is the cleanest tool to reduce bloat and make reducer logic more intuitive.

Here is a post by Chris Vibert where he gave some succinct reasons against Immutable, and for Immer:

Redux weighing in on adding Immutable:

Immer vs Immutable npm trends

As my bio says, I'm always up for learning, so I'd love to hear from others on whether Immer is the best solution for this use case, or if Immutable (or another tool) is a better alternative?

Top comments (0)