Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

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

Senior Engineer Mindset cover
Learn more

    Reader question: useReducer or XState?

    Following up from When your brain is breaking, try Stately.ai, fellow reader S. asked if useReducer could ever be relevant when using state machines in React code.

    Yes!

    You can use useReducer to implement a state machine and clean up your ternary soup. It won't have the safety guarantees of XState or the built-in support for side effects (called actions in xstate), but it's going to be a state machine.

    State machines are a way of thinking about your code. They don't care about implementation details. As I wrote in February – you're building state machines even if you don't know it.

    When Moore invented state machines in 1956 programming was done with pen and paper first. You didn't have time for trial and error. When a computer ran your code, it better be right. Hell, FORTRAN (first compiled language) didn't even come out until 1957.

    useReducer state machine example

    Using the same example as before, you start with a render like this:

    return (
    <div>
    {isLoading && <Spinner />}
    {!isLoading && !data && <NotFound />}
    {!isLoading && isError && <Ooopsies />}
    {!isLoading && data && (
    <>
    <List data={data} count={10} />
    {!showMore && <Button onClick={onShowMore} />}
    </>
    )}
    {!isLoading && data && showMore && (
    <>
    <List data={data} count={data.length} />
    <Button onClick={onHideMore} />
    </>
    )}
    </div>
    );

    and would prefer to have code like this:

    switch (state) {
    case "loading":
    return <Spinner />;
    case "not_found":
    return <NotFound />;
    case "error":
    return <Ooopsies />;
    case "show_less":
    return (
    <>
    <List data={data} count={10} />
    <Button onClick={showMore} />
    </>
    );
    case "show_more":
    return (
    <>
    <List data={data} count={data.length} />
    <Button onClick={showLess} />
    </>
    );
    default:
    return <Spinner />;
    }

    I think that's easier to work with. You may disagree, lots of people do 😅 Personally I like code that doesn't make me feel smart.

    To support that with a useReducer, you'd write a state machine like this:

    function reducer(state, action) {
    if (state === "loading") {
    switch (action.type) {
    case "loaded":
    if (action.data.length === 0) {
    return "not_found";
    } else {
    return "loaded";
    }
    case "error":
    return "error";
    }
    }
    if (state === "loaded") {
    switch (action.type) {
    case "show_more":
    return "show_more";
    }
    }
    if (state === "show_more" && action.type === "show_less") {
    return "show_less";
    }
    if (state === "show_less" && action.type === "show_more") {
    return "show_more";
    }
    }

    If you look carefully, draw a picture of possible transitions, and I didn't make mistakes, you'll get the same animation as last time:

    Simulated state machine in Stately.ai

    The useReducer hook lets you use this in a React component:

    // init with the "loading" state
    const [state, dispatch] = useReducer(reducer, "loading");

    All that remains is to call dispatch with the right actions at the right moments. Either by integrating deeply with your data loading or relying on useEffect when values change.

    As implemented, the reducer() expects calls like dispatch({type: 'error'}).

    Cheers, ~Swizec

    PS: a few readers complained the Stately article was an ad. It wasn't. I just liked it and thought you might too

    PPS: here's a series of articles and videos on refactoring a useReducer to XState

    Did you enjoy this article?

    Published on November 11th, 2022 in XState, Stately.ai, State machines, Computer science, Technical, React, Reader questions,

    Senior Mindset Book

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

    Learn more

    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

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

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