Skip to content
— 4 minute read

Persisting and restoring state in XState

David Khourshid

State machines are great for modeling state in applications. However, we often need to persist and restore state across sessions - for example, when a user closes and reopens their browser. In this article, we’ll explore how to persist and restore state in XState so your frontend applications or backend workflows can pick up where it left off.

Quick reference​

If you’re already familiar with XState, here’s a quick reference for persisting and restoring state:

import { createActor } from 'xstate';
import { someMachine } from './someMachine';

// Get the state from localStorage (if it exists)
const stateString = localStorage.getItem('some-state');

// Create the state from the string (if it exists)
const restoredState = stateString ? JSON.parse(stateString) : undefined;

const actor = createActor(someMachine, {
// Restore the state (if it exists)
state: restoredState,
});

actor.subscribe(() => {
// Persist the state to localStorage
const persistedState = actor.getPersistedState();
localStorage.setItem('some-state', JSON.stringify(persistedState));
});

actor.start();

Persisting and restoring state​

Let’s say we have a state machine that represents a user’s shopping cart:

import { createMachine, createActor, assign } from 'xstate';

const checkoutMachine = createMachine({
id: 'checkout',
initial: 'shopping',
context: {
items: [],
},
states: {
shopping: {
on: {
'item.add': {
actions: assign({
items: ({ context, event }) => {
return [...context.items, event.item];
},
}),
},
checkout: 'checkingOut',
},
},
checkingOut: {
// ...
},
},
});

const checkoutActor = createActor(machine, {
// ...
});

You may want to persist the state of this machine so that when the user comes back to the site, the items in their cart are still there, and the step in the checkout process is still the same. To do this, we need to remember to do two things:

  • Persist the state to some storage (e.g., localStorage, a database, etc.)
  • Restore the state from the storage when creating the actor

First, you should determine your persistence strategy. For this example, we’ll use the localStorage API.

Actors created with createActor have a .getPersistedState() method that returns the state that can be persisted. This state is a plain object that can be serialized to JSON using JSON.stringify(persistedState). Since the persisted state is a plain object, you can persist it to any storage that you want, as long as it can be restored as an object.

// Read the state to persist from the actor (sync)
const persistedState = actor.getPersistedState();

// Persist the state to localStorage
localStorage.setItem('some-state-key', JSON.stringify(persistedState));

Retrieve the persisted state from storage and restore it as an object when creating the actor:

// Read the persisted state from localStorage
const restoredState = localStorage.getItem('some-state-key');

const actor = createActor(machine, {
// Restore the state (if it exists)
state: restoredState,
});

actor.start();

The actor will start at the restoredState, if it exists. If restoredState is undefined, the actor will start at the initial state of the actor logic provided to createActor(logic).

Persistence strategies​

For the browser, you can:

For the server, you can:

Examples​

There are examples of persisting state that can be found in the XState git repository:

Feel free to suggest other examples at on our examples request board, or contribute your own examples!