useLocalStorage
Keep a piece of state in localStorage so it survives reloads.
useLocalStorage works like useState, but reads its first value from localStorage and writes every update back as JSON.
Compact modeKept after you reload the page.
localStorage["docs.settings.compact"] = falseImport#
typescript
import { useLocalStorage } from "@reactberry/system";
Usage#
typescript
"use client";
import { useLocalStorage } from "@reactberry/system";
import { Switch } from "@reactberry/system/blocks";
export default function CompactModeToggle() {
const [compact, setCompact] = useLocalStorage("settings.compact", false);
return <Switch label="Compact mode" value={compact} onChange={setCompact} />;
}
Examples#
Object value#
Any JSON-serialisable value works. Pass the whole new object to the setter.
{"status":"open","sort":"newest"}API#
typescript
function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void]
Parameters#
| Prop | Type | Default | Description |
|---|---|---|---|
key* | string | — | The |
initialValue* | T | — | Used when nothing is stored, during server rendering, or when reading fails. |
Returns#
A tuple:
| Prop | Type | Default | Description |
|---|---|---|---|
value | T | — | The current value. |
setValue | (value: T) => void | — | Updates the state and writes |
Notes#
- The stored value is read once, on the first render. Changing
keylater does not reload the value. - The setter takes a value only; it does not accept an updater function like
setState(prev => …). - Stored text that is not valid JSON is returned as a string. An empty stored string returns
initialValue. - The server render always uses
initialValue, so the first client render can differ from the server HTML when a value is stored. - Changes made in other tabs are not picked up.