StorageBeginnerSSR-safehooks/storage/useStorageState.ts

useStorageState

Configurable storage state.

Import

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

API

Signature

useStorageState(key, defaultValue, { type?, ... })

When to use

Use useStorageState instead of re-implementing the same pattern in multiple components.

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 · useStorageState
Editor
function Prefs() {
  const [prefs, setPrefs] = useStorageState('prefs', { density: 'comfy' }, {
    type: 'local',
  });
  return (
    <button onClick={() => setPrefs({ density: 'compact' })}>
      {prefs.density}
    </button>
  );
}
Preview

Implementation source

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

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

export interface UseStorageStateOptions<T> extends UseStorageOptions<T> {
  type?: 'local' | 'session';
}

/**
 * Configurable storage state. Defaults to localStorage.
 * Useful when the storage backend is chosen dynamically.
 */
export function useStorageState<T>(
  key: string,
  defaultValue: T,
  options: UseStorageStateOptions<T> = {},
): UseStorageReturn<T> {
  const { type = 'local', ...rest } = options;
  return useStorage(type, key, defaultValue, rest);
}

Copy-paste example

useStorageState.example.tsx
'use client';

import { useStorageState } from '@/hooks';

export function Prefs() {
  const [prefs, setPrefs] = useStorageState('prefs', { density: 'comfy' }, {
    type: 'local',
  });
  return (
    <button onClick={() => setPrefs({ density: 'compact' })}>
      {prefs.density}
    </button>
  );
}

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/useStorageState.ts for implementation details