Skip to main content
Version: 1.2.1-beta1.0

Quick Start

Wrap your app in a MnemonicProvider, then call useMnemonicKey anywhere inside it.

App.tsx
import { MnemonicProvider, useMnemonicKey } from "react-mnemonic/core";

function Counter() {
const { value: count, set } = useMnemonicKey("count", {
defaultValue: 0,
});

return (
<div>
<p>Count: {count}</p>
<button onClick={() => set((c) => c + 1)}>Increment</button>
</div>
);
}

export default function App() {
return (
<MnemonicProvider namespace="my-app">
<Counter />
</MnemonicProvider>
);
}

The counter value persists in localStorage under the key my-app.count and survives full page reloads.

Use react-mnemonic/core for the lean persisted-state path. If you need JSON Schema validation, autoschema, or migrations, import from react-mnemonic/schema or the backward-compatible root react-mnemonic entrypoint instead.

In server-rendered apps, the default contract is: render defaultValue on the server, then hydrate to persisted storage on the client. When you need a deterministic server placeholder or want to defer storage reads until after mount, see Server Rendering.

If that same key needs to appear in multiple components, define it once with defineMnemonicKey(...) and reuse the descriptor. See Canonical Key Definitions for the pattern.

If you want runtime schemas and TypeScript types to come from the same source, see Single Source of Truth Schemas.

If you want a deterministic implementation guide with invariants, decision tables, and copy-pastable recipes, see AI Overview.

If you want an external third-party signal for AI coding tools and documentation sources, see Context7 Rankings.

Persist only values you want to restore intentionally. Runtime-only UI state like loading flags, open panels, and draft search text should usually stay in plain React state instead of the persisted key.

How it works

  1. <MnemonicProvider> creates a namespaced storage scope. All keys written by hooks inside the provider are prefixed with my-app. to prevent collisions with other providers or libraries.

  2. useMnemonicKey reads the current value from storage (or returns defaultValue if the key doesn't exist), and returns a set function that writes back to storage and triggers a React re-render.

  3. The value is stored as a versioned envelope — a JSON wrapper that tracks the schema version. This powers schema migration when you upgrade your data shape later.

The return object

const { value, set, reset, remove } = useMnemonicKey<T>(key, options);
PropertyTypeDescription
valueTCurrent decoded value (or default)
set(next: T | (cur: T) => T) => voidUpdate the value (direct or updater function)
reset() => voidReset to defaultValue and persist it
remove() => voidDelete the key from storage entirely

Next steps