Code conventions

Before looking at the examples in the course, we need to define some terminology and conventions:

  • First of all, I strongly suggest cloning the repository of the course and follow along. The course is mostly practice-driven, you will get the most out of it by playing with the examples yourself
Github repository
  • Since "state" and "context" are two different concepts in XState, we are going to refer to values inside useState and useReducer as Context. This will help to avoid confusion, and to better understand how to move from those hooks to XState
import { useState } from "react";

type Context = boolean;
const initialContext = false;

export default function UseState() {
  // 👇 Refer to `useState` value as "context"
  const [context, setContext] = useState<Context>(initialContext);
  return (
    <button onClick={() => setContext(!context)}>
      {context ? "On" : "Off"}
    </button>
  );
}
  • All the types and initial values will be explicitly defined at the top of each example. This will help to understand similarities and differences between useState, useReducer and XState
import { useState } from "react";

type Context = boolean; // 👈 Explicitly define the type of the context
const initialContext = false; // 👈 Explicitly define the initial value of the context

export default function UseState() {
  //                                    👇 Explicit type and value
  const [context, setContext] = useState<Context>(initialContext);
  return (
    <button onClick={() => setContext(!context)}>
      {context ? "On" : "Off"}
    </button>
  );
}
  • At each step we will notice that some code can be reused from useState and useReducer when refactoring to XState. I will highlight this code to help bridging the gap between native hooks to the XState mental model

Don't worry if you feel overwhelmed at first. We will focus step by step on understanding all the benefits and how to get the most out of XState.

An important idea that I learned while working with XState:

XState (v5) is more about actors than state machines 💡

State machines are just one (great) way of implementing actors, but they are not always the best solution.

We are going to learn why and how during the course as we explore more complex examples.