useLocalStorage
Persists a piece of state to localStorage, kept in sync across every component using the same key — within the tab and across tabs.
useLocalStorage persists a piece of state to localStorage. Every instance using the same key stays in sync: a write in one component is reflected in every other instance immediately (no CustomEvent needed — a shared in-module listener registry handles same-tab sync), and across tabs via the native storage event.
import { useLocalStorage } from '@42/ui-react';
const [columnSizing, setColumnSizing] = useLocalStorage({
key: 'users-table',
defaultValue: {},
});It's SSR-safe: the hydration snapshot is always defaultValue, so there's no server/client mismatch to guard against — the real stored value is read in on the client shortly after mount.
Usage
Two independent hook instances sharing one key. Clicking either button updates both, since they're reading the same localStorage key.
Code
function Instance({ label }) { const [count, setCount] = useLocalStorage({ key: 'demo', defaultValue: 0 }); return ( <div> <span>{label}</span> <span>{count}</span> <Button onClick={() => setCount((c) => c + 1)}>Increment</Button> </div> );}If a write can't reach localStorage (quota exceeded, Safari private browsing), the value is kept in memory for the rest of the session instead of being lost — persistence is best-effort, but the UI never drops the update.
API
Parameters
Prop
Type
Returns
A [value, setValue, removeValue] tuple.
Prop
Type