StorageBeginnerSSR-safehooks/storage/useLocalStorage.ts

useLocalStorage

Typed localStorage state + tab sync.

Import

TypeScript
import { useLocalStorage } from '@/hooks';

API

Signature

useLocalStorage<T>(key, defaultValue, options?) → [value, set, { remove }]

When to use

Persisted preferences (theme, sidebar, filters).

SSR / Next.js

Uses defaultValue on the server; rehydrates after mount.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useLocalStorage
Editor
function Theme() {
  const [theme, setTheme, { remove }] = useLocalStorage<'light' | 'dark'>(
    'theme',
    'light',
  );

  return (
    <div>
      <p>{theme}</p>
      <button onClick={() => setTheme('dark')}>Dark</button>
      <button onClick={() => setTheme('light')}>Light</button>
      <button onClick={remove}>Clear</button>
    </div>
  );
}
Preview

Implementation source

Full library source for useLocalStorage — copy into your project when you are not installing a package yet.

hooks/storage/useLocalStorage.ts
import {
  useStorage,
  type UseStorageOptions,
  type UseStorageReturn,
} from './useStorage';

/** `localStorage`-backed state. Cross-tab sync by default. */
export function useLocalStorage<T>(
  key: string,
  defaultValue: T,
  options?: UseStorageOptions<T>,
): UseStorageReturn<T> {
  return useStorage('local', key, defaultValue, options);
}

Copy-paste example

useLocalStorage.example.tsx
'use client';

import { useLocalStorage } from '@/hooks';

export function Theme() {
  const [theme, setTheme, { remove }] = useLocalStorage<'light' | 'dark'>(
    'theme',
    'light',
  );

  return (
    <div>
      <p>{theme}</p>
      <button onClick={() => setTheme('dark')}>Dark</button>
      <button onClick={() => setTheme('light')}>Light</button>
      <button onClick={remove}>Clear</button>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Only store JSON-serializable values. Theme keys should match across tabs.
  • Source of truth: open hooks/storage/useLocalStorage.ts for implementation details