Skip to content
Version: XState v5

@xstate/svelte

The @xstate/svelte package contains utilities for using XState with Svelte.

Templates​

Use the following templates to get started quickly with XState and Svelte:

Installation​

Install the latest versions of both xstate and @xstate/svelte. xstate is a peer dependency of @xstate/svelte.

npm install xstate @xstate/svelte

API​

useMachine(machine, options?)​

A function that creates an actor from the given machine and starts a service that runs for the lifetime of the component.

Arguments

Returns { snapshot, send, actorRef}:

  • snapshot - A Svelte store representing the current state of the machine
  • send - A function that sends events to the running actor ref.
  • actorRef - The created actor ref.

useSelector(actorRef, selector, compare?, getSnapshot?)​

A function that returns Svelte store representing the selected value from the snapshot of an actorRef, such as a service. The store will only be updated when the selected value changes, as determined by the optional compare function.

Arguments

  • actorRef - An actor ref
  • selector - a function that takes in an actor’s current state (snapshot) as an argument and returns the desired selected value.
  • compare (optional) - a function that determines if the current selected value is the same as the previous selected value.

Examples​

Coming soon

Matching States​

When using hierarchical and parallel machines, the state values will be objects, not strings. In this case, it is best to use state.matches(...).

{#if $state.matches('idle')}
//
{:else if $state.matches({ loading: 'user' })}
//
{:else if $state.matches({ loading: 'friends' })}
//
{/if}

Persisted and Rehydrated State​

You can persist and rehydrate state with useMachine(...) via options.snapshot:

// Get the persisted state config object from somewhere, e.g. localStorage
const persistedState = JSON.parse(
localStorage.getItem('some-persisted-state-key'),
);

const { snapshot, send } = useMachine(someMachine, {
snapshot: persistedState,
});

// state will initially be that persisted state, not the machine’s initialState