useLocalStorage
A custom hook that manages state synchronized with localStorage.
pnpm dlx shadcn@latest add @reactusekit/use-local-storage
import { useLocalStorage } from "@/hooks/use-local-storage"
function App() {
const [theme, setTheme] = useLocalStorage("theme", "light")
const [name, setName, removeName] = useLocalStorage("userName", "")
return (
<div>
<div>
<label>Theme: </label>
<select value={theme} onChange={(e) => setTheme(e.target.value)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div>
<label>Name: </label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button onClick={removeName}>Clear</button>
</div>
<p>Current theme: {theme}</p>
<p>Hello, {name || "Guest"}!</p>
</div>
)
}
import { useLocalStorage } from "@/hooks/use-local-storage"
type InstallationType = "cli" | "manual"
function ConfigExample() {
// Store raw string values without JSON quotes
const [installType, setInstallType] = useLocalStorage<InstallationType>(
"installationType",
"cli",
{
serializer: {
read: (value: string) => (value === "manual" ? "manual" : "cli"),
write: (value: InstallationType) => value, // Stores "cli" instead of "\"cli\""
},
}
)
// Custom serializer for dates
const [lastLogin, setLastLogin] = useLocalStorage("lastLogin", new Date(), {
serializer: {
read: (value: string) => new Date(value),
write: (value: Date) => value.toISOString(),
},
})
return (
<div>
<p>Install Type: {installType}</p>
<button onClick={() => setInstallType("manual")}>Set Manual</button>
<button onClick={() => setInstallType("cli")}>Set CLI</button>
<p>Last Login: {lastLogin.toLocaleString()}</p>
<button onClick={() => setLastLogin(new Date())}>
Update Login Time
</button>
</div>
)
}
Parameter | Type | Description |
---|
key | string | The localStorage key to use |
initialValue | T | The initial value if no value exists |
options | object | Configuration options |
Option | Type | Default | Description |
---|
serializer | object | JSON | Custom serializer with read/write methods |
syncData | boolean | true | Whether to sync data across tabs |
initializeWithValue | boolean | true | Whether to initialize with localStorage value |
Name | Type | Description |
---|
value | T | The current value |
setValue | (value: T | ((val: T) => T)) => void | Function to set the value |
removeValue | () => void | Function to remove the value from storage |