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.
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.
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.
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.
And you use it like this:
Isn't that more readable, easier to understand, and way easier to debug? Got a problem, change the map. Done.
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
useStates 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.
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.
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:
Hooks the machine up to your component.
state is the current state machine state,
send is like dispatch – sends actions.
send instead of
And you read current state like this:
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 ✌️
[^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
Here's how it works 👇
And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️