Docs
useLocalStorage
Store, retrieve, and synchronize data from the browser's localStorage API with useLocalStorage.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-local-storage
Usage
"use client"
import { useLocalStorage } from "@/hooks/use-local-storage"
export function Component() {
const [count, setCount] = useLocalStorage("count", 0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
)
}
Example
Complex Object Type
interface UserSettings {
theme: "light" | "dark"
notifications: boolean
}
const [settings, setSettings] = useLocalStorage<UserSettings>("user-settings", {
theme: "light",
notifications: true,
})
Lazy Initial State
const [authToken, setAuthToken] = useLocalStorage<string>("auth-token", () =>
window.crypto.randomUUID()
)
Key Differences from useSessionStorage
-
Storage Lifetime:
sessionStorage
data is cleared when the page session ends (e.g., when the tab is closed).localStorage
persists even after the browser is closed and reopened.
-
Scope:
sessionStorage
is scoped to the current tab/window.localStorage
is shared across all tabs/windows of the same origin.
-
Use Cases:
- Use
useSessionStorage
for temporary data that should not persist beyond the current session. - Use
useLocalStorage
for persistent data that should remain available across sessions.
- Use
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
key | string | The key used to access the local storage value. | - | No |
initialValue | T | The initial value to use if there is no item in the local storage with the provided key. | - | Yes |
Return Values
Name | Type | Description |
---|---|---|
localState | T | The current state of the value stored in local storage. |
handleSetState | Function | A function to set the state of the value in the local storage. This function accepts a new value or a function that returns a new value. The value is also saved in the local storage under the provided key. |