DEV Community

Håkan Fahlstedt
Håkan Fahlstedt

Posted on

YPSKA #12 Immer

Immutability is kind of hard in JavaScript, at least it takes a bit of work to make it happen.

To make it easier, there's of course a library for that, Immer. Immer uses something called producers to update state and also keep that new state immutable. The basic idea is like this:

const newState = produce(oldState, draft => {
   // modify state
});

So you pass in the old state and a function that takes a "draftState" and makes modifications to it. The returned state is really a read-only object produced by Object.freeze().

If you need immutability in your JavaScript/TypeScript, check out Immer.

Less than ten minutes margin from missing a day in this series ;-)

Top comments (0)