Skip to content

Illustrated.dev

Toggle Nav
ExplainersSketchesAbout

Immutable State with Immer

Immutability and state are two developer buzzwords it took me forever to "get."

Their underlying meanings aren't necessarily that complex.
But it's tough to fully comprehend what they mean, and why they're important, until you see them in action.

State just means the way an application is at a single point in time.

For example, if we've typed "how does CSS grid work" into the search bar, and there are three checkboxes ticked, and we have a dropdown menu open that's the current "state" of things.
If we close the menu that's a state change.

Behind the scenes in apps we have to account for every state an app could be in (which gets expontential very quicky). This is usually called "managing state" and appears to be a neverending problem.


Immutable State is one approach to solving our complex state problem – it simply means making a second copy of things before you change them.

It's the same as copying and pasting a new ImportantThing_Version2_Draft.md document before liberally changing enourmous chunks of it. Then when you realise your poor editing choices and want to go back to the original version, it's there waiting for you.

Writing immutable code is a wildly popular concept in general. And a good idea when you don't want to muck everything up.


You're probably already imagining the complications of this approach in a world of finite computing power. Making copies of copies of copies of copies for every small state change leads to a boatload of code.

Luckily, Michel Weststrate just came up with an elegant new tool that helps handle this predicament in Javascript.

It's called Immer, and does a lot of fancy optimization work that helps manage immutable state in a sane way.

On top of builing this nifty new tool, Michel has also recorded and released a new egghead course that explains how to use it.

immutable javascript data structures with immer

Despite my allegic intolerance towards thinking about state and immutability, this course turned out to be a delight.

Michel walks us through building a gifting app with React & Immer that seamlessly handles all the messy state work.

immer 1

Visually drawing out how all the functions and drafts and edits fit together was essential for this one. I wouldn't have grokked it otherwise.

immer 2

immer 3

If you're currently allergic to state & immutability as well, this might be the time to re-test your tolerances and see if Immer can help cure it.


The Full Sketchnote


immer mini

Want to learn more?

A high-res & printable version of the sketchnote, plus the full course is avaliable here on the Immutable JavaScript Data Structures with Immer page.