Introducing Immer: Immutability the easy way – Hacker Noon

  • The producer function receives one argument, the draft, which is a proxy to the current state you passed in.
  • The currentState will be untouched during this process.Because immer uses structural sharing, and our example producer above didn’t modify anything, the next state above is simply the state we started with.Let’s take look at what happens when we start modifying the draft in our producer.
  • It is not too bad in this simple case, but this process has to be repeated for every action, and on every level in which we want modify something.We have to make sure to return the existing state if the reducer doesn’t do anythingWith Immer, we only need to reason…
  • Both the original reducer and the new one behave exactly the same.No strings attachedThe idea to produce the next immutable state by modifying a temporarily draft isn’t new.
  • This will create a new function that will execute the producer when it’s passed in a state.

Immutable, structurally shared data structures are a great paradigm for storing state. Especially when combined with an event-sourcing architecture. However, there is a cost to pay. In a language…

Introducing Immer: Immutability the easy way

Immutable, structurally shared data structures are a great paradigm for storing state. Especially when combined with an event-sourcing architecture. However, there is a cost to pay. In a language like JavaScript where immutability is not built into the language, producing a new state from the previous one is a boring, boiler-platy task. To prove the point: The Redux-ecosystem-links page alone lists 67(!) packages to help you to deal with immutable data structures in Redux.

is an elegant concept in a language like ClojureScript, any JavaScript counterparts will basically rely on ugly string paths. Which are error-prone, hard to type-check and requires learning yet another set of API functions by heart to be pro-efficient.

does.

Tip: if you don’t like reading, you can also watch the egghead tutorial for immer

Immer works by writing producers, and the simplest producer possible looks like this:

The produce function takes two arguments. The currentState and a producer function. The current state determines our starting point, and the producer expresses what needs to happen to it. The producer function receives one argument, the draft, which is a proxy to the current state you passed in. Any modification you make to the draft will be recorded and used to produce nextState. The currentState will be untouched during this process.

Because immer uses structural sharing, and our example producer above didn’t modify anything, the next state above is…

Introducing Immer: Immutability the easy way – Hacker Noon