Swizec Teller - a geek with a hatswizec.com

    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.

    Click through for source
    Click through for source

    How you create a mess

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

    Click through for source
    Click through for source

    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.

    conspiracy_theory_board giphy

    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.

    Click through for source
    Click through for source

    And you use it like this:

    Click through for source
    Click through for source


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

    Click through for source
    Click through for source

    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 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 😍

    Click through for source
    Click through for source

    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.

    Click through for source
    Click through for source

    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:

    Click through for source
    Click through for source

    Click through for source
    Click through for source

    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

    Click through for source
    Click through for source

    And you read current state like this:

    Click through for source
    Click through for source

    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


    [^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

    Did you enjoy this article?

    Published on August 10th, 2020 in Computer Science, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works πŸ‘‡

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    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. πŸ‘Œ"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer?Β I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    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

    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 ❀️