StorageBeginnerSSR-safehooks/storage/useStorage.ts

useStorage

Pick local or session storage.

Import

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

API

Signature

useStorage(type, key, defaultValue, options?)

When to use

Use useStorage 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 · useStorage
Editor
function Flag() {
  const [v, setV] = useStorage('session', 'flag', false);
  return <button onClick={() => setV((x) => !x)}>{String(v)}</button>;
}
Preview

Implementation source

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

hooks/storage/useStorage.ts
import {
  useCallback,
  useEffect,
  useState,
  type Dispatch,
  type SetStateAction,
} from 'react';
import { isBrowser } from '../utility/isBrowser';
import {
  getStorage,
  jsonSerializer,
  readStorageValue,
  writeStorageValue,
  type Serializer,
} from './storage';

export interface UseStorageOptions<T> {
  serializer?: Serializer<T>;
  /** Sync across tabs via storage events. @default true for localStorage */
  sync?: boolean;
}

export type UseStorageReturn<T> = [
  T,
  Dispatch<SetStateAction<T>>,
  { remove: () => void },
];

/**
 * Generic storage-backed state (local or session).
 * SSR-safe: uses defaultValue until mounted.
 */
export function useStorage<T>(
  type: 'local' | 'session',
  key: string,
  defaultValue: T,
  options: UseStorageOptions<T> = {},
): UseStorageReturn<T> {
  const serializer = options.serializer ?? jsonSerializer<T>();
  const sync = options.sync ?? type === 'local';
  const storage = getStorage(type);

  const [value, setValue] = useState<T>(() =>
    isBrowser()
      ? readStorageValue(storage, key, defaultValue, serializer)
      : defaultValue,
  );

  // Hydrate after mount (SSR mismatch safety)
  useEffect(() => {
    setValue(readStorageValue(getStorage(type), key, defaultValue, serializer));

  }, [key, type]);

  const set: Dispatch<SetStateAction<T>> = useCallback(
    (update) => {
      setValue((prev) => {
        const next =
          typeof update === 'function'
            ? (update as (p: T) => T)(prev)
            : update;
        writeStorageValue(getStorage(type), key, next, serializer);
        return next;
      });
    },
    [key, type, serializer],
  );

  const remove = useCallback(() => {
    try {
      getStorage(type)?.removeItem(key);
    } catch {
      // ignore
    }
    setValue(defaultValue);
  }, [key, type, defaultValue]);

  useEffect(() => {
    if (!isBrowser() || !sync || type !== 'local') return;

    const onStorage = (event: StorageEvent) => {
      // Ignore events from other storage areas when storageArea is present.
      if (
        event.storageArea != null &&
        event.storageArea !== window.localStorage
      ) {
        return;
      }
      if (event.key !== key) return;
      if (event.newValue === null) {
        setValue(defaultValue);
        return;
      }
      try {
        setValue(serializer.read(event.newValue));
      } catch {
        setValue(defaultValue);
      }
    };

    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, [key, sync, type, defaultValue, serializer]);

  return [value, set, { remove }];
}

Copy-paste example

useStorage.example.tsx
'use client';

import { useStorage } from '@/hooks';

export function Flag() {
  const [v, setV] = useStorage('session', 'flag', false);
  return <button onClick={() => setV((x) => !x)}>{String(v)}</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/useStorage.ts for implementation details