Docs
useSessionStorage
Store, retrieve, and synchronize data from the browser’s sessionStorage API with useSessionStorage.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-session-storage
Usage
"use client"
import { useSessionStorage } from "@/hooks/use-session-storage"
export function Component() {
const [count, setCount] = useSessionStorage("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] = useSessionStorage<UserSettings>(
"user-settings",
{ theme: "light", notifications: true }
)
Lazy Initial State
const [authToken, setAuthToken] = useSessionStorage<string>("auth-token", () =>
window.crypto.randomUUID()
)
Key Differences from useLocalStorage
-
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 sessionStorage value. | - | No |
initialValue | T | The initial value to use if there is no item in the sessionStorage with the provided key. | undefined | Yes |
Return Values
Name | Type | Description |
---|---|---|
sessionState | T | The current state of the value stored in sessionStorage. |
handleSetState | Function | A function to set the state of the value in the sessionStorage. This function accepts a new value or a function that returns a new value. The value is also saved in the sessionStorage under the provided key. |