Skip to content
usefy

useLocalStorage

Storage

A powerful React hook for persisting state in localStorage with automatic same-tab and cross-tab synchronization

Install

$ npm install @usefy/use-local-storage

Quick start

useLocalStorage.tsx
import { useLocalStorage } from "@usefy/use-local-storage";

function ThemeToggle() {
  const [theme, setTheme, removeTheme] = useLocalStorage("theme", "light");

  return (
    <div>
      <p>Current theme: {theme}</p>
      <button onClick={() => setTheme("dark")}>Dark</button>
      <button onClick={() => setTheme("light")}>Light</button>
      <button onClick={removeTheme}>Reset</button>
    </div>
  );
}

API reference

useLocalStorage<T>(key, initialValue, options?)

A hook that persists state in localStorage with automatic synchronization.

Parameters

ParameterTypeDescription
keystringThe localStorage key
initialValueT | () => TInitial value or lazy initializer function
optionsUseLocalStorageOptions<T>Configuration options

Options

OptionTypeDefaultDescription
serializer(value: T) => stringJSON.stringifyCustom serializer function
deserializer(value: string) => TJSON.parseCustom deserializer function
syncTabsbooleantrueSync value across browser tabs
onError(error: Error) => voidCallback for error handling

Returns [T, SetValue<T>, RemoveValue]

IndexTypeDescription
[0]TCurrent stored value
[1]Dispatch<SetStateAction<T>>Function to update value (same as useState)
[2]() => voidFunction to remove value and reset to initial

Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in storage