Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-session-storage
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>
)
}interface UserSettings {
theme: "light" | "dark"
notifications: boolean
}
const [settings, setSettings] = useSessionStorage<UserSettings>(
"user-settings",
{ theme: "light", notifications: true }
)const [authToken, setAuthToken] = useSessionStorage<string>("auth-token", () =>
window.crypto.randomUUID()
)useLocalStorageStorage 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:
useSessionStorage for temporary data that should not persist beyond the current session.useLocalStorage for persistent data that should remain available across sessions.| 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 |
| 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. |
Count: 0
Click to increment the counter and watch the count persist in session storage!