Skip to content
Bunshi
GitHub

XState

Background

XState is a state management and orchestration solution for JavaScript and TypeScript apps.

It uses event-driven programming, state machines, statecharts, and the actor model to handle complex logic in predictable, robust, and visual ways. XState provides a powerful and flexible way to manage application and workflow state by allowing developers to model logic as actors and state machines. It integrates well with React, Vue, Svelte, and other frameworks and can be used in the frontend, backend, or wherever JavaScript runs.

Component state

Bunshi helps you create xstate machines per component or other scopes, instead of only globally.

import { ComponentScope, molecule, onMount, use } from "bunshi";
import { assign, createMachine, interpret } from "xstate";

interface CounterContext {
  count: number;
}

type CounterEvent = {
  type: "INCREMENT";
};

export const CountMolecule = molecule(() => {
  use(ComponentScope);

  const countMachine = createMachine<CounterContext, CounterEvent>({
    id: "counter",
    context: { count: 0 },
    on: {
      INCREMENT: {
        actions: assign({ count: (ctx) => ctx.count + 1 }),
      },
    },
  });

  const actor = interpret(countMachine);

  onMount(() => {
    actor.start();
    return () => actor.stop();
  });
  return actor;
});

Global state

You can use Xstate to define a machine that is shared across your application, too.

import { molecule, onMount } from "bunshi";
import { assign, createMachine, interpret } from "xstate";

interface CounterContext {
  count: number;
}

type CounterEvent = {
  type: "INCREMENT";
};

export const CountMolecule = molecule(() => {
  const countMachine = createMachine<CounterContext, CounterEvent>({
    id: "counter",
    context: { count: 0 },
    on: {
      INCREMENT: {
        actions: assign({ count: (ctx) => ctx.count + 1 }),
      },
    },
  });

  const actor = interpret(countMachine);

  onMount(() => {
    actor.start();
    return () => actor.stop();
  });
  return actor;
});

Why Bunshi with xstate?

Bunshi helps scope your XState services. Notice how in this example you didn’t need to touch your Counter component to move the state to being global or component scoped. Bunshi helps remove boilerplate and centralize your state management tools.

  • Use XState for global state stores
  • Move state without touching components
  • Use the vanilla javascript API of XState
  • Share machines across different pages, components or sections
  • Keep your state logic decoupled from your UI