Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Stores and Context

Persisting State and Undo History

Save SolidJS signals and stores to localStorage with an effect, restore them safely on load, and build undo and redo with store snapshots and the unwrap helper.

State that disappears on refresh is annoying: a draft message, a chosen theme, a half-filled settings form. Because Solid state is plain reactive data, saving it is mostly a matter of reading it in an effect and writing it somewhere. The reverse, loading, happens once when the app starts.

In this lesson you will persist a signal and a store, handle the failure cases that real browsers produce, and then build undo and redo on top of store snapshots.

The live editors on this site run inside a sandboxed frame, where localStorage is unavailable and throws. The persistence code below is therefore read-only and shown in the real-project form; the live examples use an in-memory stand-in with the same shape so you can watch the logic work.

Saving and restoring a signal

The pattern has three parts: read the saved value when the signal is created, wrap storage access in try/catch, and write with an effect.

JavaScript
import { createSignal, createEffect } from "solid-js";

function createStoredSignal(key, initial) {
  let start = initial;
  try {
    const raw = localStorage.getItem(key);
    if (raw !== null) start = JSON.parse(raw);
  } catch {
    // storage blocked, or the saved text was not valid JSON: use the default
  }

  const [value, setValue] = createSignal(start);

  createEffect(() => {
    const current = value();            // tracked: reruns on every change
    try {
      localStorage.setItem(key, JSON.stringify(current));
    } catch {
      // quota exceeded or private mode: ignore, the app still works
    }
  });

  return [value, setValue];
}

export const [theme, setTheme] = createStoredSignal("theme", "light");

Why try/catch twice? localStorage can throw when it is disabled, full, or in some private windows, and JSON.parse throws when someone (or an older version of your app) saved something unexpected. A tutorial site, a settings page, a game: none of them should crash because a preference could not be saved.

Persisting a store

A store holds nested data, and createEffect only tracks what you read. To save the whole store, read all of it. Solid's unwrap gives the raw object, but it does not read every property, so the dependable way is to serialize it: JSON.stringify(state) walks every property through the proxy and therefore subscribes to all of them.

JavaScript
import { createStore } from "solid-js/store";
import { createEffect } from "solid-js";

const saved = (() => {
  try { return JSON.parse(localStorage.getItem("settings")); } catch { return null; }
})();

export const [settings, setSettings] = createStore(
  saved ?? { fontSize: 16, notifications: true, tags: [] }
);

createEffect(() => {
  const text = JSON.stringify(settings);   // reads everything, tracks everything
  try { localStorage.setItem("settings", text); } catch {}
});

This runs after any change anywhere in the store. For small stores that is fine. For large ones, save with a debounce (see async patterns).

A store saved on every change (in-memory stand-in)

Each write triggers a save, and the last line shows the nested array edit was noticed too.

Validating what you load

Saved data is input from outside your program. An older version of the app may have saved a different shape, and the user can edit storage by hand. Before trusting it, merge it onto defaults and check types:

JavaScript
const defaults = { fontSize: 16, notifications: true };

function load() {
  try {
    const data = JSON.parse(localStorage.getItem("settings"));
    return {
      fontSize: typeof data?.fontSize === "number" ? data.fontSize : defaults.fontSize,
      notifications: typeof data?.notifications === "boolean"
        ? data.notifications
        : defaults.notifications,
    };
  } catch {
    return { ...defaults };
  }
}

Adding a version number to what you save ({ v: 2, data: ... }) makes later migrations simple.

Undo and redo with snapshots

Undo needs a history of earlier states. With a store you can record a snapshot after each change: a deep copy made with structuredClone of the unwrapped data. Keep two stacks, past and future.

flowchart LR
  P["past stack"] -- "undo: pop" --> C["current state"]
  C -- "undo: push old current" --> F["future stack"]
  F -- "redo: pop" --> C

Undo moves the current state onto the future stack and restores the last past entry. A new edit clears the future.

Undo and redo for a store

Two details matter. The snapshot is taken before the change, so the past stack holds earlier states. And restoring uses reconcile, which diffs the old data against the snapshot and updates only what differs; see produce, reconcile and unwrap. Without reconcile, setState(snapshotObject) would merge instead of replace.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why wrap localStorage access in try/catch?

    Both storage access and parsing can throw; the app should fall back to defaults instead of crashing.
  2. 2. How can an effect track every property of a nested store?

    Effects only track what they read. Serializing walks every property through the proxy.
  3. 3. When should the undo snapshot be taken?

    The past stack must hold the state as it was before the edit, so you can go back to it.
  4. 4. What should happen to the redo stack when the user makes a new edit?

    A new edit starts a new timeline, so the old redo entries no longer apply.

Summary

  • Persist with an effect that reads the state and writes it, and restore once at creation.
  • Guard storage and parsing with try/catch, and validate loaded data against defaults.
  • To save a whole store, read all of it (JSON.stringify).
  • Undo and redo are two stacks of structuredClone(unwrap(state)) snapshots restored with reconcile.

Next: Loading Data with createResource