Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Pages and UI / Browser storageRead Markdown
    On this page

    Bind browser storage to components

    Define schema-validated storage keys and bind local or session storage reactively to Preact and React components.

    Storage is persisted client state. For in-memory coordination across Preact island roots on one page, use stores instead.

    Define keys once

    #

    Use the framework-owned Zod export and colocate reusable keys with the feature that owns them:

    src/features/preferences/storage-keys.ts
    import { createStorageKey } from "brix/storage";
    import { z } from "brix/zod";
    
    export const themeKey = createStorageKey("theme", z.enum(["light", "dark"]));
    export const profileKey = createStorageKey(
      "profile",
      z.object({ displayName: z.string(), visits: z.number().int().nonnegative() }),
    );
    

    A StorageKey is the plain { key, schema } definition. Reuse it rather than repeating a string and schema or spreading the definition. Reads, writes, and hooks also accept an inline (key, schema) pair, but a schema is never optional. Removal accepts either a storage key or a string because no value needs validation.

    Choose stable, application-specific key names. Schema changes must tolerate data written by an older application version or deliberately treat it as missing.

    Use reactive hooks

    #
    src/features/preferences/ThemePicker.tsx
    "use island";
    
    import { useLocalStorage } from "brix/hooks";
    import { themeKey } from "./storage-keys.ts";
    
    export function ThemePicker() {
      const theme = useLocalStorage(themeKey);
    
      return (
        <select
          aria-label="Theme"
          value={theme.value ?? "light"}
          onChange={(event) => {
            const value = event.currentTarget.value;
            if (value === "light" || value === "dark") theme.set(value);
          }}
        >
          <option value="light">Light</option>
          <option value="dark">Dark</option>
        </select>
      );
    }
    

    On the first server render, the select shows Light. After the island mounts, an existing valid saved value replaces that fallback. Choosing Dark persists "dark"; another mounted hook for the same key updates immediately, and another same-origin tab receives the local-storage change.

    useLocalStorage and useSessionStorage return:

    • value, the parsed schema output or null when absent, invalid, or unavailable.
    • set(value), a write typed to the schema input. It validates the value, persists it, and then updates every subscriber with the parsed output.
    • remove(), which removes the item and updates subscribers.

    Neither binding applies a theme for you: this example persists a preference, and application styling must consume it separately.

    Inputs and transformed schemas

    #

    Brix persists the validated input JSON, then applies the schema again whenever it reads. For example, a string-to-number transform accepts and stores "12", while value is the number 12. Persisting the transformed output would make the next read invalid for that schema.

    Both Preact and React bindings validate the supplied input and its JSON-normalized snapshot before persisting. For domain values such as dates, use an ISO-string input schema transformed to Date output and pass date.toISOString() to set, not a Date accepted by z.date(). See wire-input schemas.

    Hook writes never throw. If validation, serialization, or persistence fails, set leaves storage and every subscriber unchanged and does not report the failure. When the UI needs to explain a rejected value, check it with the key's schema.safeParse(value) before calling set. Raw helpers, by contrast, throw on schema failures.

    Synchronization

    #

    Hooks for the same storage object and key synchronize within the current document, including changes made through Brix raw helpers. Writes made directly through localStorage.setItem bypass that notification; use the Brix helpers instead. Local-storage hooks also consume browser storage events, so another tab's write or clear() re-renders subscribers. Session storage is tab-scoped and does not synchronize across tabs.

    SSR and hydration

    #

    Local and session hooks intentionally return null on the server and on the browser's initial render, then read storage in an effect. Keep the fallback deterministic so hydration starts from the same markup. Denied storage access or an invalid saved value also produces null rather than breaking the component.

    If storage access becomes unavailable on a later render, the hook immediately returns null and stops listening to the old storage in its effect. Rendering again after access returns reads the persisted value. Brix does not poll for permission changes. A failed write against an available storage object instead preserves the previous value.

    Malformed JSON and ordinary schema validation issues yield null. Exceptions thrown by application transforms or refinements propagate during reads, including rendering; Brix does not treat those programmer callback failures as invalid saved data. Use Zod validation issues for expected rejections, and keep transforms and refinements pure because parsing may run during rendering.

    Changing keys, schemas, or storage objects

    #

    Replacing a hook's schema revalidates the last observed stored JSON on that render. The displayed value and subsequent writes use the new schema; incompatible saved input yields null. This does not migrate or rewrite storage. Inline schemas are supported without a render loop, but reusable schemas avoid repeated parsing.

    Each returned set captures that render's storage, key, and schema. A suspended or abandoned render cannot change validation for the still-committed UI. The setter's identity changes when the storage, key, or schema changes; use a stable schema when callback stability matters, and include set in dependencies rather than retaining a setter from an older render.

    Changing the key or replacing a custom storage object returns null on the transition render until an effect reads the new identity. The hook never shows the previous key or storage object's value under the new identity, including notifications arriving from the old subscription. set and remove already target the new identity. Missing new keys stay null, and the effect disconnects the old subscription.

    Use a custom storage object

    #

    For an app-specific Storage implementation, use useStorage(customStorage, storageKey) from the matching Preact or React binding. Unlike the local/session wrappers, this generic hook reads the supplied storage during its initial render, so its first render can already show saved data. Later identity changes still use the transition behavior described above.

    Use storage in React

    #

    React applications import useStorage, useLocalStorage, and useSessionStorage from @brix/react instead of brix/hooks and do not add an island directive. Keys, return shape, validation, and synchronization are the same.

    Continue with use typed browser storage helpers.