Skip to main content

Function: useLocalStorage()

@arolariu/components


@arolariu/components / useLocalStorage

Function: useLocalStorage()

useLocalStorage<T>(key, initialValue): [T, (value) => void]

Defined in: hooks/useLocalStorage.tsx:46

Persists state to localStorage with SSR safety and JSON serialization.

Type Parameters

T

T

The type of the value being stored.

Parameters

key

string

The localStorage key to store the value under.

initialValue

T

The default value to use if no value is found in localStorage.

Returns

[T, (value) => void]

A tuple containing the current value and a setter function.

Remarks

This hook synchronizes state with localStorage, allowing data to persist across page refreshes and browser sessions. It is SSR-safe and returns the initial value on the server until hydration completes. The hook also syncs state across tabs/windows via the storage event and handles JSON parse errors gracefully by falling back to the initial value.

Examples

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

return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Toggle theme (current: {theme})
</button>
);
}
function ShoppingCart() {
const [cart, setCart] = useLocalStorage<Product[]>("cart", []);

return (
<button onClick={() => setCart((prev) => [...prev, newProduct])}>
Add to cart ({cart.length} items)
</button>
);
}
// was this page useful?