Skip to main content

useLocalStorage

Location: src/hooks/useLocalStorage.js

Overview

A useState-like hook that persists its value to localStorage. The value is automatically JSON-serialized on write and JSON-parsed on read. If the key does not exist in storage, the provided initial value is used. Supports both direct values and updater functions (like useState).

Note: Per project conventions, do not use this hook for sensitive data. See the anti-patterns section in CLAUDE.md.

Signature

function useLocalStorage<T>(
key: string,
initialValue: T
): [T, (value: T | ((prev: T) => T)) => void]

Parameters

ParameterTypeRequiredDescription
keystringYesThe localStorage key to read from and write to.
initialValueTYesThe default value to use when the key does not exist in localStorage.

Return Value

Returns a tuple (array) identical in shape to useState:

IndexTypeDescription
[0]TThe current stored value (deserialized from localStorage, or the initial value).
[1](value: T | ((prev: T) => T)) => voidSetter function. Accepts either a new value or an updater function. Updates both React state and localStorage.

Usage

function Settings() {
const [theme, setTheme] = useLocalStorage('theme', 'light');

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

With updater function

function Counter() {
const [count, setCount] = useLocalStorage('counter', 0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(prev => prev + 1)}>Increment</button>
</div>
);
}

Last updated: 2026-02-07