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
| Parameter | Type | Default | Description |
|---|---|---|---|
key | string | — | The storage key used to retrieve and store data. |
defaultValue | T | (() => 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].
| Property | Type | Description |
|---|---|---|
[0] | T | The current stored value. |
[1] | Dispatch<SetStateAction<T>> | Function to update the stored value (accepts a value or an updater function). |
Behavior
- Wraps
useStorageinternally with the"local"storage type. - Persists values to
localStorageand reads the initial value from it, falling back todefaultValue. - Syncs state across browser tabs/windows: when the same key changes in another tab, the
storageevent updates this hook's value. - Removes the key from
localStoragewhen the value isundefined. - Uses JSON parse/stringify with error handling, and guards against
localStoragebeing 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.