evergreen

Immutable Data with Immer and Personal Assistant Bots

Illustrated notes on how work with immutable data in the Immer state library

Let’s talk about immutable data. With socks. And personal assistant bots. I know, you’re already so excited.

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.


Okay now you’re all caught up on the jargon. Lets get to some illustrated notes.

These are from a course Michel Weststrate made about their elegant new tool Immer – it helps handle manage immutable state in a sane way.

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

Immer is a small JS library that makes working with immutable state easy and enjoyable. It's like a small assistant that helps you make copies and edits to documents.
Immer's produce function does all the work - it takes a state object and runs a draft function telling the state how it should change.
The product function supports currying - which is when we nest functions inside others to make our code composable
We can easily use immer with other libraries like React and write callback functions using immer's produce function

CSS is awesome cup

Yes the cup in the illustration is based on this classic CSS one that I don’t own, but kind of want to.

Want more illustrated notes on web development?

Take a look at Testing Apps with Cypress , The JAMStack, Gatsby & Contentful or A Fresh Serving of JavaScript ES2019