useLocalStorage
StorageA powerful React hook for persisting state in localStorage with automatic same-tab and cross-tab synchronization
Install
$ npm install @usefy/use-local-storageQuick 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
| Parameter | Type | Description |
|---|---|---|
key | string | The localStorage key |
initialValue | T | () => T | Initial value or lazy initializer function |
options | UseLocalStorageOptions<T> | Configuration options |
Options
| Option | Type | Default | Description |
|---|---|---|---|
serializer | (value: T) => string | JSON.stringify | Custom serializer function |
deserializer | (value: string) => T | JSON.parse | Custom deserializer function |
syncTabs | boolean | true | Sync value across browser tabs |
onError | (error: Error) => void | — | Callback for error handling |
Returns [T, SetValue<T>, RemoveValue]
| Index | Type | Description |
|---|---|---|
[0] | T | Current stored value |
[1] | Dispatch<SetStateAction<T>> | Function to update value (same as useState) |
[2] | () => void | Function 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.