swizec.com

#### Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

# When your brain is breaking, try XState

Ever built code that's like a Jenga tower of conditional logic?

It always starts off easy. If A is true, show X, otherwise Y.

Oh but if B is true then show Z, unless A is also true, then you need Y and Z. And if C happens after A is true, but not after B is true, then you ...

Aaaaand you've got a mess. A piece of code that's going to be fun to maintain.

This happens a lot. Sometimes fast, sometimes after months of polishing your logic to include every edge case.

And that's okay. Messes happen.

It's what you do with your mess that matters.

## How you create a mess

Here's a mess, I made it just for you ❤️

Check the checkboxes to get different colors. Looks silly in this example and I assure you it happens all the time.

Like when I was building an insurance intake form that shows fields depending on previous answers and what the API says is even possible in this particular case 😅

Messes happen when you're dealing with a combinatorial explosion. Every new condition doubles the number of possible states.

3 variables give us 8 possible states. 4 makes 16. 5 is 32.

That's booleans.

Imagine enums with 4 possible states. 3 of those and you're looking at 64 combinations.

🤯

Your first inclination is to write chains of conditionals. Cover the 3 or 4 happy-path cases and done.

The other 60 are edge cases you find in production through bug reports. You fix those.

And you create long and complex conditionals that nobody on your team can read. Each bug fix creates 5 new bugs.

Everything's connected, nothing makes sense.

## How you fix the mess with hashmaps

Your way out of this mess is a stable mapping of states to values. Easiest to do with a hashmap.

You can start with a truth table to get your bearings. Great for boolean logic, difficult for enums. You run out of dimensions 😅

Truth table for the mess above looks like this:

You can turn that into a hashmap of states. A piece of data that tells you how the code behaves.

```.css-1yb0ye3{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-1yb0ye3 .comment,.css-1yb0ye3 .prolog,.css-1yb0ye3 .doctype,.css-1yb0ye3 .cdata,.css-1yb0ye3 .punctuation{color:#b6ad9a;}.css-1yb0ye3 .namespace{opacity:0.7;}.css-1yb0ye3 .tag,.css-1yb0ye3 .operator,.css-1yb0ye3 .number{color:#063289;}.css-1yb0ye3 .property,.css-1yb0ye3 .function{color:#b29762;}.css-1yb0ye3 .tag-id,.css-1yb0ye3 .selector,.css-1yb0ye3 .atrule-id{color:#2d2006;}.css-1yb0ye3 .attr-name{color:#896724;}.css-1yb0ye3 .boolean,.css-1yb0ye3 .string,.css-1yb0ye3 .entity,.css-1yb0ye3 .url,.css-1yb0ye3 .attr-value,.css-1yb0ye3 .keyword,.css-1yb0ye3 .control,.css-1yb0ye3 .directive,.css-1yb0ye3 .unit,.css-1yb0ye3 .statement,.css-1yb0ye3 .regex,.css-1yb0ye3 .at-rule{color:#728fcb;}.css-1yb0ye3 .placeholder,.css-1yb0ye3 .variable{color:#93abdc;}.css-1yb0ye3 .deleted{text-decoration-line:line-through;}.css-1yb0ye3 .inserted{text-decoration-line:underline;}.css-1yb0ye3 .italic{font-style:italic;}.css-1yb0ye3 .important,.css-1yb0ye3 .bold{font-weight:700;}.css-1yb0ye3 .important{color:#896724;}.css-1yb0ye3 .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x{font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;font-family:monospace;color:#728fcb;background-color:#faf8f5;font-size:0.9em;padding-left:0;padding-right:0;}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}.css-o6ar0x .comment,.css-o6ar0x .prolog,.css-o6ar0x .doctype,.css-o6ar0x .cdata,.css-o6ar0x .punctuation{color:#b6ad9a;}.css-o6ar0x .namespace{opacity:0.7;}.css-o6ar0x .tag,.css-o6ar0x .operator,.css-o6ar0x .number{color:#063289;}.css-o6ar0x .property,.css-o6ar0x .function{color:#b29762;}.css-o6ar0x .tag-id,.css-o6ar0x .selector,.css-o6ar0x .atrule-id{color:#2d2006;}.css-o6ar0x .attr-name{color:#896724;}.css-o6ar0x .boolean,.css-o6ar0x .string,.css-o6ar0x .entity,.css-o6ar0x .url,.css-o6ar0x .attr-value,.css-o6ar0x .keyword,.css-o6ar0x .control,.css-o6ar0x .directive,.css-o6ar0x .unit,.css-o6ar0x .statement,.css-o6ar0x .regex,.css-o6ar0x .at-rule{color:#728fcb;}.css-o6ar0x .placeholder,.css-o6ar0x .variable{color:#93abdc;}.css-o6ar0x .deleted{text-decoration-line:line-through;}.css-o6ar0x .inserted{text-decoration-line:underline;}.css-o6ar0x .italic{font-style:italic;}.css-o6ar0x .important,.css-o6ar0x .bold{font-weight:700;}.css-o6ar0x .important{color:#896724;}.css-o6ar0x .highlight{background:hsla(0, 0%, 70%, .5);}```const STATE_MAP = {
"0-0-0": { green: 1, red: 0, blue: 0 },
"0-0-1": { green: 1, red: 0, blue: 0 },
"0-1-0": { green: 0, red: 0, blue: 0 },
"0-1-1": { green: 0, red: 1, blue: 1 },
"1-0-0": { green: 0, red: 0, blue: 1 },
"1-0-1": { green: 1, red: 1, blue: 1 },
"1-1-0": { green: 1, red: 0, blue: 0 },
"1-1-1": { green: 1, red: 0, blue: 0 },
}
``````

And you use it like this:

``````const key = `\${Number(a)}-\${Number(b)}-\${Number(c)}`
const showGreen = STATE_MAP[key].green
const showRed = STATE_MAP[key].red
const showBlue = STATE_MAP[key].blue
``````

😍

Isn't that more readable, easier to understand, and way easier to debug? Got a problem, change the map. Done.

## How you fix the mess with state machines

What a hashmap can't do, is guard against impossible states. What if you don't want users to click A when B and C are true? 🤔

That's when you need a state machine, my friend. They're fun to build, tricky to get right, and different to think about than you're used to.

`useReducer` is a state machine. Redux, too. `useState` if you squint your eyes.

Here's a state machine for each of the `useState`s in our smol mess example.

Circles are states, arrows are transitions. You can draw a state machine like this for almost anything[^1].

That's where XState shines – it's designed for state machines. It can even visualize them for you 😍

Yeah, no wonder that form broke my brain.

## Using XState

Now, how do you use XState to fix the mess above?

First you need to define the state machine. Flip your mindset from mapping states to transitioning between states.

I like to do this in the XState visualizer. Helps you see what you're doing.

👆 Click to see the full machine in XState visualizer

You define XState machines by listing states, their meta data, and performable actions. Each action points to the next state.

``````const smolMessMachine = Machine({
id: 'smolMess',
initial: '0-0-0',
states: {
'0-0-0': {
on: {
A: '1-0-0',
B: '0-1-0',
C: '0-0-1'
},
meta: { green: 1, red: 0, blue: 0 }
},
'0-0-1': {
on: {
A: '1-0-1',
B: '0-1-1',
C: '0-0-0'
},
meta: { green: 1, red: 0, blue: 0 }
},
``````

This looks like a lot of work compared to a hashmap, I know, but it's invaluable when you want to prevent some transitions. Or you need to run side-effects when states are entered/exited.

XState can do all that, it's great.

Putting this in our smol mess, you get this:

``````const [state, send] = useMachine(smolMessMachine)
``````

Hooks the machine up to your component. `state` is the current state machine state, `send` is like dispatch – sends actions.

Checkboxes use `send` instead of `setX`

``````<label>
<input type="checkbox" checked={a} onChange={() => send("A")} />A
</label>
``````

And you read current state like this:

``````// 0-0-0 👉 [false, false, false]
const [a, b, c] = state.value.split("-").map(Number).map(Boolean)

const showGreen = !!state.meta[`smolMess.\${state.value}`].green,
showRed = !!state.meta[`smolMess.\${state.value}`].red,
showBlue = !!state.meta[`smolMess.\${state.value}`].blue
``````

Your code would have better-named states than my example. No need to translate with .map :)

The meta data nests under your state machine name because you can have multiple running in parallel. That's when XState becomes pure wow 😉

And unless I made a mistake, all 3 codesandboxes should behave the same. But 2 of those are way easier to debug ✌️

Happy hacking

Cheers,
~Swizec

[^1] finite state machines can't solve every solvable problem. Pushdown automata (state machines with a stack) are more powerful and Turing machines (state machine with an infinite memory) can solve anything

PS: you can use XState in server code, too

Published on August 10th, 2020 in Computer Science, Technical, React, State Machines

Semantically similar articles hand-picked by GPT-4

### Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

Created by Swizec with ❤️