Installation
Installxstate and @xstate/svelte:
Quick Start
The@xstate/svelte package provides functions to use XState with Svelte, returning Svelte stores:
Available Functions
The@xstate/svelte package provides these functions:
useActor(logic, options?)- Creates and starts an actor from any XState logicuseActorRef(logic, options?)- Returns just the actor ref without reactive storeuseMachine(machine, options?)- Alias foruseActor, specifically typed for state machinesuseSelector(actorRef, selector, compare?)- Derives and subscribes to a selected value from an actor
Return Values
useActor / useMachine
Returns an object with:snapshot- A Svelte readable store containing the current snapshotsend- Function to send events to the actoractorRef- The underlying actor reference
useSelector
Returns a Svelte readable store containing the selected value:Svelte Stores
All reactive values are returned as Svelte readable stores, which means:- Use the
$prefix to access values in templates:$snapshot - Subscribe to changes with the
.subscribe()method - Automatically unsubscribe when component is destroyed
Lifecycle
The actor is automatically started when created and stopped when the component is destroyed:- Actor is started immediately via
createActor(logic, options).start() onDestroy- Actor is stopped when component is destroyed
TypeScript
All functions are fully typed when using TypeScript:Next Steps
useActor
Learn about the useActor function
useSelector
Select derived values from actor snapshots