It’s fairly easy to setup when you deal with simple data structure. For example, if you want to update your
content at your Store’s root, you can do something like :
But when you’re starting to have a more complex data structure with nested objects and arrays, things became quickly tricky and after the Callbacks and the Promises of Hell, please welcome the “Reducer of Hell” (thanks to Object Spread goodness)!
For example if your want to update a specific post’s
content attribute :
Dirty, right ? Ok, maybe you can be smarter and start modeling something more decoupled and less nested, or maybe not… Thankfully, Michel Weststrate, the smart guy behind MobX, had provided us a more elegant solution for making state mutations : Immer.js!
You simply have to wrap your reducer inside the
immer method and replace your dirty mutation code by a more elegant one, same as native
Object prototype methods.
For the same complex example using Immer, your reducer will look like :
Holy cow! Yep, my first reaction too. Now you can handle complex Store data without having dirty reducers. Complex data; clean, typed and performant reducers, what else?
I invite you to read all the good stuff of Immer.js on it repository. There is a great and visual explanation of how it works under the hood and what are all the benefits of using it (aside of reducing your code size by 1,000).