DEV Community

Jason M
Jason M

Posted on

Simplying State Management with Immer: Some Thoughts

Not sure about the rest of you, but I find that with any mildly complex state in react / redux applications, updating state for objects deeper inside the state can be a pain.

Here's some state:

some state

Suppose we want to make a change to the description for item 3 (id) in purchase 7 for account 1. Without a helper library, we'd do something like this:

a complicated way to update state

All of this just to update a single field. The excess spreading makes the code hard to understand, and also introduces more opportunities to mess up and introduce bugs. Wouldn't it be better if we could just do something like this?

Alt Text

This code is a lot cleaner, more intelligible, and leaves less room for introducing bugs. Unfortunately, when we're working with state in react and redux, we need to avoid mutating state directly, so without a helping hand, we cant use the latter code snippet. Fortunately, Immer (a javascript immutability library), can provide us with that helping hand.

Alt Text

Top comments (0)