JavaScript

Simple State Machine

by @admin
12h ago
Apr 28, 2026
Public
A lightweight finite state machine that defines valid states and allowed transitions between them. Attempting an invalid transition throws an error. Supports entry/exit hooks per state for side effects. Useful for modelling UI flows (idle → loading → success/error), auth states, and multi-step forms.
JavaScript
function createMachine(config) {
  let current = config.initial;

  return {
    get state() { return current; },
    can(event) {
      return event in (config.states[current]?.on ?? {});
    },
    send(event) {
      const transitions = config.states[current]?.on ?? {};
      const next = transitions[event];
      if (!next) throw new Error(`No transition '${event}' from '${current}'`);
      config.states[current]?.exit?.();
      current = next;
      config.states[current]?.enter?.();
      return current;
    },
  };
}

// Usage
const machine = createMachine({
  initial: 'idle',
  states: {
    idle:    { on: { FETCH: 'loading' } },
    loading: { on: { SUCCESS: 'done', ERROR: 'failed' }, enter: () => console.log('Loading…') },
    done:    { on: { RESET: 'idle' } },
    failed:  { on: { RESET: 'idle' } },
  },
});

machine.send('FETCH');    // → loading
machine.send('SUCCESS');  // → done
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.