Packages

xstate

5.33.4 · 7 Nov 2026MIT9M / weekRepositoryHomepagenpmAtom feed

Your version

201 stable releases, newest first, by release line. Notes are quoted as the maintainers published them.

  1. 4.30.4

    4 Mar 2022

    Reading the note…

  2. 4.30.3

    1 Mar 2022

    Reading the note…

  3. 4.30.2

    22 Feb 2022

    Reading the note…

  4. 4.30.1

    15 Feb 2022

    Reading the note…

  5. 4.30.0

    12 Feb 2022
    • Deprecated

      Marked all phantom properties on the StateMachine type as deprecated. This deprioritized them in IDEs so they don't popup as first suggestions during property access.

    • All actions are now available in the actions variable when importing: import { actions } from 'xstate'

    • Persisted state can now be easily restored to a state compatible with the machine without converting it to a State instance first:

      // Persisting a state
      someService.subscribe(state => {
        localStorage.setItem('some-state', JSON.stringify(state));
      });
      
      // Restoring a state
      const stateJson = localStorage.getItem('some-state');
      
      // No need to convert `stateJson` object to a state!
      const someService = interpret(someMachine).start(stateJson);
  6. 4.29.0

    27 Jan 2022
    • Using config.schema becomes the preferred way of "declaring" TypeScript generics with this release:

      createMachine({
          schema: {
              context: {} as { count: number },
              events: {} as { type: 'INC' } | { type: 'DEC' }
          }
      })

      This allows us to leverage the inference algorithm better and unlocks some exciting possibilities for using XState in a more type-strict manner.

    • Added the ability to tighten TS declarations of machine with generated metadata. This opens several exciting doors to being able to use typegen seamlessly with XState to provide an amazing typing experience.

      With the VS Code extension, you can specify a new attribute called tsTypes: {} in your machine definition:

      const machine = createMachine({
        tsTypes: {}
      });

      The extension will automatically add a type assertion to this property, which allows for type-safe access to a lot of XState's API's.

      ⚠️ This feature is in beta. Actions/services/guards/delays might currently get incorrectly annotated if they are called "in response" to always transitions or raised events. We are working on fixing this, both in XState and in the typegen.

    • Added t(), which can be used to provide types for schema attributes in machine configs:

      import { t, createMachine } from 'xstate';
      
      const machine = createMachine({
        schema: {
          context: t<{ value: number }>(),
          events: t<{ type: 'EVENT_1' } | { type: 'EVENT_2' }>()
        }
      });
  7. 4.28.1

    21 Jan 2022

    Reading the note…

  8. 4.28.0

    18 Jan 2022
    • Added interop observable symbols to ActorRef so that actor refs are compatible with libraries like RxJS.

    • Generated IDs for invocations that do not provide an id are now based on the state ID to avoid collisions:

      createMachine({
        id: 'test',
        initial: 'p',
        states: {
          p: {
            type: 'parallel',
            states: {
              // Before this change, both invoke IDs would be 'someSource',
              // which is incorrect.
              a: {
                invoke: {
                  src: 'someSource'
                  // generated invoke ID: 'test.p.a:invocation[0]'
                }
              },
              b: {
                invoke: {
                  src: 'someSource'
                  // generated invoke ID: 'test.p.b:invocation[0]'
                }
              }
            }
          }
        }
      });
    • The sendTo(actorRef, event) action creator introduced in 4.27.0, which was not accessible from the package exports, can now be used just like other actions:

      import { actions } from 'xstate';
      
      const { sendTo } = actions;
  9. 4.27.0

    30 Dec 2021
    • The sendTo(actorRef, event) action creator has been introduced. It allows you to specify the recipient actor ref of an event first, so that the event can be strongly typed against the events allowed to be received by the actor ref:

      // ...
      entry: sendTo(
        (ctx) => ctx.someActorRef,
        { type: 'EVENT_FOR_ACTOR' }
      ),
      // ...
    • The state.can(...) method no longer unnecessarily executes assign() actions and instead determines if a given event will change the state by reading transition data before evaluating actions.

    • Fixed an issue with stopped children sometimes starting their own child actors. This could happen when the child was stopped synchronously (for example by its parent) when transitioning to an invoking state.

  10. 4.26.1

    22 Nov 2021

    Reading the note…

  11. 4.26.0

    1 Nov 2021
    • The description property is a new top-level property for state nodes and transitions, that lets you provide text descriptions:

      const machine = createMachine({
        // ...
        states: {
          active: {
            // ...
            description: 'The task is in progress',
            on: {
              DEACTIVATE: {
                // ...
                description: 'Deactivates the task'
              }
            }
          }
        }
      });

      Future Stately tooling will use the description to render automatically generated documentation, type hints, and enhancements to visual tools.

    • Add optional type parameter to narrow type returned by EventFrom. You can use it like this:

      type UpdateNameEvent = EventFrom<typeof userModel>;
    • The tags property was missing from state's definitions. This is used when converting a state to a JSON string. Since this is how we serialize states within @xstate/inspect this has caused inspected machines to miss the tags information.

  12. 4.25.0

    16 Sep 2021
    • Removed the ability to pass a model as a generic to createMachine, in favour of model.createMachine. This lets us cut an overload from the definition of createMachine, meaning errors become more targeted and less cryptic.

      This means that this approach is no longer supported:

      const model = createModel({});
      
      const machine = createMachine<typeof model>();

      If you're using this approach, you should use model.createMachine instead:

      const model = createModel({});
      
      const machine = model.createMachine();
    • Fixed a regression in the inline actions type inference in models without explicit action creators.

      const model = createModel(
        { foo: 100 },
        {
          events: {
            BAR: () => ({})
          }
        }
      );
      
      model.createMachine({
        // `ctx` was of type `any`
        entry: ctx => {},
        exit: assign({
          // `ctx` was of type `unknown`
          foo: ctx => 42
        })
      });
  13. 4.24.1

    15 Sep 2021

    Reading the note…

  14. 4.24.0

    14 Sep 2021
    • You can now know if an event will cause a state change by using the new state.can(event) method, which will return true if an interpreted machine will "change" the state when sent the event, or false otherwise:

      const machine = createMachine({
        initial: 'inactive',
        states: {
          inactive: {
            on: {
              TOGGLE: 'active'
            }
          },
          active: {
            on: {
              DO_SOMETHING: { actions: ['something'] }
            }
          }
        }
      });
      
      const state = machine.initialState;
      
      state.can('TOGGLE'); // true
      state.can('DO_SOMETHING'); // false
      
      // Also takes in full event objects:
      state.can({
        type: 'DO_SOMETHING',
        data: 42
      }); // false

      A state is considered "changed" if any of the following are true:

      See state.changed (documentation) for more details.

    • A regression was fixed where actions were being typed as never if events were specified in createModel(...) but not actions:

      const model = createModel(
        {},
        {
          events: {}
        }
      );
      
      model.createMachine({
        // These actions will cause TS to not compile
        entry: 'someAction',
        exit: { type: 'someObjectAction' }
      });
  15. 4.23.4

    3 Sep 2021

    Reading the note…

  16. 4.23.3

    31 Aug 2021

    Reading the note…

  17. 4.23.2

    30 Aug 2021

    Reading the note…

  18. 4.23.1

    24 Jul 2021

    Reading the note…

  19. 4.23.0

    16 Jul 2021
    • There is a new .preserveActionOrder (default: false) setting in the machine configuration that preserves the order of actions when set to true. Normally, actions are executed in order except for assign(...) actions, which are prioritized and executed first. When .preserveActionOrder is set to true, assign(...) actions will not be prioritized, and will instead run in order. As a result, actions will capture the intermediate context values instead of the resulting context value from all assign(...) actions.

      // With `.preserveActionOrder: true`
      const machine = createMachine({
        context: { count: 0 },
        entry: [
          ctx => console.log(ctx.count), // 0
          assign({ count: ctx => ctx.count + 1 }),
          ctx => console.log(ctx.count), // 1
          assign({ count: ctx => ctx.count + 1 }),
          ctx => console.log(ctx.count) // 2
        ],
        preserveActionOrder: true
      });
      
      // With `.preserveActionOrder: false` (default)
      const machine = createMachine({
        context: { count: 0 },
        entry: [
          ctx => console.log(ctx.count), // 2
          assign({ count: ctx => ctx.count + 1 }),
          ctx => console.log(ctx.count), // 2
          assign({ count: ctx => ctx.count + 1 }),
          ctx => console.log(ctx.count) // 2
        ]
        // preserveActionOrder: false
      });
    • Add type for Symbol.observable to the Interpreter to improve the compatibility with RxJS.

    • Existing actors can now be identified in spawn(...) calls by providing an id. This allows them to be referenced by string:

      const machine = createMachine({
        context: () => ({
          someRef: spawn(someExistingRef, 'something')
        }),
        on: {
          SOME_EVENT: {
            actions: send('AN_EVENT', { to: 'something' })
          }
        }
      });
  20. 4.22.0

    6 Jul 2021
    • The model created from createModel(...) now provides a .createMachine(...) method that does not require passing any generic type parameters:

      const model = createModel(/* ... */);
      
      -const machine = createMachine<typeof model>(/* ... */);
      +const machine = model.createMachine(/* ... */);
    • Actors can now be invoked/spawned from reducers using the fromReducer(...) behavior creator:

      import { fromReducer } from 'xstate/lib/behaviors';
      
      type CountEvent = { type: 'INC' } | { type: 'DEC' };
      
      const countReducer = (count: number, event: CountEvent): number => {
        if (event.type === 'INC') {
          return count + 1;
        } else if (event.type === 'DEC') {
          return count - 1;
        }
      
        return count;
      };
      
      const countMachine = createMachine({
        invoke: {
          id: 'count',
          src: () => fromReducer(countReducer, 0)
        },
        on: {
          INC: {
            actions: forwardTo('count')
          },
          DEC: {
            actions: forwardTo('count')
          }
        }
      });
    • Actors can now be spawned directly in the initial machine.context using lazy initialization, avoiding the need for intermediate states and unsafe typings for immediately spawned actors:

      const machine = createMachine<{ ref: ActorRef<SomeEvent> }>({
        context: () => ({
          ref: spawn(anotherMachine, 'some-id') // spawn immediately!
        })
        // ...
      });
  21. 4.20.2

    1 Jul 2021

    Reading the note…

  22. 4.20.1

    25 Jun 2021

    Reading the note…

  23. 4.20.0

    1 Jun 2021
    • All spawned and invoked actors now have a .getSnapshot() method, which allows you to retrieve the latest value emitted from that actor. That value may be undefined if no value has been emitted yet.

      const machine = createMachine({
        context: {
          promiseRef: null
        },
        initial: 'pending',
        states: {
          pending: {
            entry: assign({
              promiseRef: () => spawn(fetch(/* ... */), 'some-promise')
            })
          }
        }
      });
      
      const service = interpret(machine)
        .onTransition(state => {
          // Read promise value synchronously
          const resolvedValue = state.context.promiseRef?.getSnapshot();
          // => undefined (if promise not resolved yet)
          // => { ... } (resolved data)
        })
        .start();
      
      // ...
    • Preserve StateMachine type when .withConfig() and .withContext() modifiers are used on a machine.

  24. 4.19.2

    26 May 2021

    Reading the note…

  25. 4.19.1

    5 May 2021

    Reading the note…

  26. 4.19.0

    29 Apr 2021
    • Tags can now be added to state node configs under the .tags property:

      const machine = createMachine({
        initial: 'green',
        states: {
          green: {
            tags: 'go' // single tag
          },
          yellow: {
            tags: 'go'
          },
          red: {
            tags: ['stop', 'other'] // multiple tags
          }
        }
      });

      You can query whether a state has a tag via state.hasTag(tag):

      const canGo = state.hasTag('go');
      // => `true` if in 'green' or 'yellow' state
    • In callback invokes, the types of callback and onReceive are properly scoped to the machine TEvent.

  27. 4.18.0

    16 Apr 2021
    • Allow machines to communicate with the inspector even in production builds.

    • There is now support for "combinatorial machines" (state machines that only have one state):

      const testMachine = createMachine({
        context: { value: 42 },
        on: {
          INC: {
            actions: assign({ value: ctx => ctx.value + 1 })
          }
        }
      });

      These machines omit the initial and state properties, as the entire machine is treated as a single state.

    • Provide a convenience type for getting the Interpreter type based on the StateMachine type by transferring all generic parameters onto it. It can be used like this: InterpreterFrom<typeof machine>

  28. 4.17.1

    27 Mar 2021

    Reading the note…

  29. 4.17.0

    21 Mar 2021
    • The schema property has been introduced to the machine config passed into createMachine(machineConfig), which allows you to provide metadata for the following:

      This metadata can be accessed as-is from machine.schema:

      const machine = createMachine({
        schema: {
          // Example in JSON Schema (anything can be used)
          context: {
            type: 'object',
            properties: {
              foo: { type: 'string' },
              bar: { type: 'number' },
              baz: {
                type: 'object',
                properties: {
                  one: { type: 'string' }
                }
              }
            }
          },
          events: {
            FOO: { type: 'object' },
            BAR: { type: 'object' }
          }
        }
        // ...
      });

      Additionally, the new createSchema() identity function allows any schema "metadata" to be represented by a specific type, which makes type inference easier without having to specify generic types:

      import { createSchema, createMachine } from 'xstate';
      
      // Both `context` and `events` are inferred in the rest of the machine!
      const machine = createMachine({
        schema: {
          context: createSchema<{ count: number }>(),
          // No arguments necessary
          events: createSchema<{ type: 'FOO' } | { type: 'BAR' }>()
        }
        // ...
      });
    • Event creators can now be modeled inside of the 2nd argument of createModel(), and types for both context and events will be inferred properly in createMachine() when given the typeof model as the first generic parameter.

      import { createModel } from 'xstate/lib/model';
      
      const userModel = createModel(
        // initial context
        {
          name: 'David',
          age: 30
        },
        // creators (just events for now)
        {
          events: {
            updateName: (value: string) => ({ value }),
            updateAge: (value: number) => ({ value }),
            anotherEvent: () => ({}) // no payload
          }
        }
      );
      
      const machine = createMachine<typeof userModel>({
        context: userModel.initialContext,
        initial: 'active',
        states: {
          active: {
            on: {
              updateName: {
                /* ... */
              },
              updateAge: {
                /* ... */
              }
            }
          }
        }
      });
      
      const nextState = machine.transition(
        undefined,
        userModel.events.updateName('David')
      );
  30. 4.16.2

    7 Feb 2021

    Reading the note…

  31. 4.16.1

    5 Feb 2021

    Reading the note…

  32. 4.16.0

    15 Jan 2021
    • An opt-in createModel() helper has been introduced to make it easier to work with typed context and events.

      See #1439 for more details.

      import { createMachine } from 'xstate';
      import { createModel } from 'xstate/lib/model'; // opt-in, not part of main build
      
      interface UserContext {
        name: string;
        age: number;
      }
      
      type UserEvents =
        | { type: 'updateName'; value: string }
        | { type: 'updateAge'; value: number }
      
      const userModel = createModel<UserContext, UserEvents>({
        name: 'David',
        age: 30
      });
      
      const assignName = userModel.assign({
        name: (_, e) => e.value // correctly typed to `string`
      }, 'updateName'); // restrict to 'updateName' event
      
      const machine = createMachine<UserContext, UserEvents>({
        context: userModel.context,
        initial: 'active',
        states: {
          active: {
            on: {
              updateName: {
                actions: assignName
              }
            }
          }
        }
      });
  33. 4.15.4

    6 Jan 2021

    Reading the note…

  34. 4.15.3

    29 Dec 2020

    Reading the note…

  35. 4.15.2

    23 Dec 2020

    Reading the note…

  36. 4.15.1

    7 Dec 2020

    Reading the note…

  37. 4.15.0

    6 Dec 2020
    • Spawned/invoked actors and interpreters are now typed as extending ActorRef (e.g., SpawnedActorRef) rather than Actor or Interpreter. This unification of types should make it more straightforward to provide actor types:

      import {
      - Actor
      + ActorRef
      } from 'xstate';
      
      // ...
      
      interface SomeContext {
      - server?: Actor;
      + server?: ActorRef<ServerEvent>;
      }

      It's also easier to specify the type of a spawned/invoked machine with ActorRefFrom:

      import {
        createMachine,
      - Actor
      + ActorRefFrom
      } from 'xstate';
      
      const serverMachine = createMachine<ServerContext, ServerEvent>({
        // ...
      });
      
      interface SomeContext {
      - server?: Actor; // difficult to type
      + server?: ActorRefFrom<typeof serverMachine>;
      }
    • Fixed an issue with history state entering a wrong state if the most recent visit in its parent has been caused by a transient transition.

  38. 4.14.1

    25 Nov 2020

    Reading the note…

  39. 4.14.0

    5 Nov 2020
    • Expressions can now be used in the stop() action creator:

      // ...
      actions: stop(context => context.someActor);
    • The return type of spawn(machine) will now be Actor<State<TContext, TEvent>, TEvent>, which is a supertype of Interpreter<...>.

    • Exit actions will now be properly called when an invoked machine reaches its final state. See #1109 for more details.

  40. 4.13.0

    27 Aug 2020
    • Fix type ExtractStateValue so that it generates a type actually describing a State.value

    • Improved TypeScript type-checking performance a little bit by using distributive conditional type within TransitionsConfigArray declarations instead of a mapped type. Kudos to @amcasey, some discussion around this can be found here

    • Fixed an issue with not being able to run XState in Web Workers due to assuming that window or global object is available in the executing environment, but none of those are actually available in the Web Workers context.

  41. 4.12.0

    17 Aug 2020
    • The Action type was simplified, and as a result, you should see better TypeScript performance.

    • The invoke.src property now accepts an object that describes the invoke source with its type and other related metadata. This can be read from the services option in the meta.src argument:

      const machine = createMachine(
        {
          initial: 'searching',
          states: {
            searching: {
              invoke: {
                src: {
                  type: 'search',
                  endpoint: 'example.com'
                }
                // ...
              }
              // ...
            }
          }
        },
        {
          services: {
            search: (context, event, { src }) => {
              console.log(src);
              // => { endpoint: 'example.com' }
            }
          }
        }
      );

      Specifying a string for invoke.src will continue to work the same; e.g., if src: 'search' was specified, this would be the same as src: { type: 'search' }.

    • All TTypestate type parameters default to { value: any; context: TContext } now and the parametrized type is passed correctly between various types which results in more accurate types involving typestates.

  42. 4.11.0

    2 Jul 2020
    • Breaking

      Improved type inference for InvokeConfig['data']. This has required renaming data property on StateNode instances to doneData. This property was never meant to be a part of the public API, so we don't consider this to be a breaking change.

    • Deprecated

      New property introduced for eventless (transient) transitions: always, which indicates a transition that is always taken when in that state. Empty string transition configs for transient transitions are deprecated in favor of always:

      // ...
      states: {
        playing: {
      +   always: [
      +     { target: 'win', cond: 'didPlayerWin' },
      +     { target: 'lose', cond: 'didPlayerLose' },
      +   ],
          on: {
            // ⚠️ Deprecation warning
      -     '': [
      -       { target: 'win', cond: 'didPlayerWin' },
      -       { target: 'lose', cond: 'didPlayerLose' },
      -     ]
          }
        }
      }
      // ...

      The old empty string syntax ('': ...) will continue to work until V5.

    • The resolved value of the invoke.data property is now available in the "invoke meta" object, which is passed as the 3rd argument to the service creator in options.services. This will work for all types of invoked services now, including promises, observables, and callbacks.

      const machine = createMachine({
        initial: 'pending',
        context: {
          id: 42
        },
        states: {
          pending: {
            invoke: {
              src: 'fetchUser',
              data: {
                userId: (context) => context.id
              },
              onDone: 'success'
            }
          },
          success: {
            type: 'final'
          }
        }
      },
      {
        services: {
          fetchUser: (ctx, _, { data }) => {
            return fetch(`some/api/user/${data.userId}`)
              .then(response => response.json());
          }
        }
      }
  43. 4.10.0

    20 May 2020
    • The types for the send() and sendParent() action creators have been changed to fix the issue of only being able to send events that the machine can receive. In reality, a machine can and should send events to other actors that it might not be able to receive itself. See #711 for more information.

    • Previously, state.matches(...) was problematic because it was casting state to never if it didn't match the state value. This is now fixed by making the Typestate resolution more granular.

    • Actions from a restored state provided as a custom initial state to interpret(machine).start(initialState) are now executed properly. See #1174 for more information.

  44. 4.9.1

    17 Apr 2020

    Reading the note…

  45. 4.9.0

    15 Apr 2020
    • Simplify the TransitionConfigArray and TransitionConfigMap types in order to fix excessively deep type instantiation TypeScript reports. This addresses #1015.

    • Added support for conditional actions. It's possible now to have actions executed based on conditions using following:

      entry: [
        choose([
          { cond: ctx => ctx > 100, actions: raise('TOGGLE') },
          {
            cond: 'hasMagicBottle',
            actions: [assign(ctx => ({ counter: ctx.counter + 1 }))]
          },
          { actions: ['fallbackAction'] }
        ])
      ];

      It works very similar to the if-else syntax where only the first matched condition is causing associated actions to be executed and the last ones can be unconditional (serving as a general fallback, just like else branch).

    • Cleanup internal structures upon receiving termination events from spawned actors.

  46. 4.8.0

    4 Mar 2020
    • The machine can now be safely JSON-serialized, using JSON.stringify(machine). The shape of this serialization is defined in machine.schema.json and reflected in machine.definition.

      Note that onEntry and onExit have been deprecated in the definition in favor of entry and exit.

    • Fixed memory leak - State objects had been retained in closures.

  47. 4.7.8

    4 Feb 2020

    Reading the note…

  48. 4.7.7

    24 Jan 2020

    Reading the note…

  49. 4.7.6

    7 Jan 2020

    Reading the note…

  50. 4.7.5

    28 Dec 2019

    Reading the note…

A whole project to check? Paste its package.json in the dependency check: every deprecated, outdated or vulnerable dependency, with what to upgrade to. Free, no account.