Skip to main content

useLocalStorage

useLocalStorage is a custom hook for syncing state with localStorage, with automatic synchronization across browser tabs and windows.

Usage

import { useLocalStorage } from "hookify-react";

export default function UseLocalStorage() {
const [name, setName] = useLocalStorage<string>("name", "default name");

return (
<div>
<p>Your name is {name}</p>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
keystringThe storage key used to retrieve and store data.
defaultValueT | (() => T)The default value, or a lazy initializer function returning it, used when no value is found in localStorage.

Return Value

A tuple [value, setValue].

PropertyTypeDescription
[0]TThe current stored value.
[1]Dispatch<SetStateAction<T>>Function to update the stored value (accepts a value or an updater function).

Behavior

  • Wraps useStorage internally with the "local" storage type.
  • Persists values to localStorage and reads the initial value from it, falling back to defaultValue.
  • Syncs state across browser tabs/windows: when the same key changes in another tab, the storage event updates this hook's value.
  • Removes the key from localStorage when the value is undefined.
  • Uses JSON parse/stringify with error handling, and guards against localStorage being unavailable (private mode, sandboxed iframes).

SSR Safety

useLocalStorage is SSR-safe. On the server it falls back to defaultValue and performs no storage access, making it safe for server-rendered apps.