useLocalStorage
Reactive, fully-typed localStorage value.
Reads the stored value on mount (falling back to initial), writes through whenever .current is assigned, and optionally syncs across browser tabs.
SSR-safe - renders initial on the server and hydrates on mount. Parse and quota errors are tolerated.
Basic usage
Read .current reactively and assign to write through to localStorage. Reload the page - the value persists.
Persisted theme: system
Stored under key sv5ui-docs-demo-theme - survives a page reload.
<script lang="ts">
import { useLocalStorage } from 'sv5ui';
const theme = useLocalStorage('theme', 'system');
</script>
<p>Current theme: <strong>{theme.current}</strong></p>
<div class="flex gap-2">
{#each ['system', 'light', 'dark'] as t}
<button onclick={() => (theme.current = t)}>{t}</button>
{/each}
</div>Typed objects
Pass a type parameter and an object as the initial value. The hook serializes with JSON by default - assign a whole new object to update.
fontSize: 16px | compact: false
<script lang="ts">
import { useLocalStorage } from 'sv5ui';
interface UserPrefs {
fontSize: number;
compact: boolean;
language: string;
}
const prefs = useLocalStorage<UserPrefs>('user-prefs', {
fontSize: 16,
compact: false,
language: 'en'
});
function toggleCompact() {
prefs.current = { ...prefs.current, compact: !prefs.current.compact };
}
</script>
<p>Font size: {prefs.current.fontSize}px</p>
<p>Compact: {prefs.current.compact}</p>
<button onclick={toggleCompact}>Toggle compact</button>Custom serializer
When the value type is not natively JSON-serializable (e.g. Set, Map, Date), supply a serializer with parse and stringify.
Code reference - see snippet for the Set serializer pattern.
<script lang="ts">
import { useLocalStorage } from 'sv5ui';
// Store a Set - JSON.stringify does not handle Set natively
const favorites = useLocalStorage('favorites', new Set<string>(), {
serializer: {
parse: (raw) => new Set(JSON.parse(raw)),
stringify: (value) => JSON.stringify([...value])
}
});
function toggle(id: string) {
const next = new Set(favorites.current);
next.has(id) ? next.delete(id) : next.add(id);
favorites.current = next;
}
</script>Parameters
| Parameter | Type | Default |
|---|---|---|
key | string | - |
initial | T | - |
Options
| Option | Type | Default |
|---|---|---|
serializer | { parse, stringify } | JSON |
syncTabs | boolean | true |
Return
| Property | Type | - |
|---|---|---|
current | T | - |