useStorage
A simple typesafe state manager using localStorage or sessionStorage.
Features
- Built-in Validation: Validate with zod, valibot, arktype or with a simple function.
- Tab Sync: The state is synced across multiple browser tabs when using the
localStorage
. - Component Sync: The state is synced across all components.
Installation
Quick Start
Setup the State
Use defineCookie to configure validation rules and the type of storage.
Read and Write.
Changes to the state are synchronized across all instances of the hook and across browser tabs.
Storage updates are automatically synchronized across all instances of the hook and across browser tabs.
Validation
To ensure data integrity, the storage should be validated.
👉 Functional validation
For simple cases you can use a function to validate the storage.
👉 Schema validation
For more complex cases you can use a schema to validate the storage. Compatible validation libraries include zod 3.24+, valibot 1.0+ or arktype 2.0+. Check out Standard Schema for more info.
Outside of React
defineStorage
returns a standalone utility object that provides methods to get
, set
or clear
the value outside of React components.
Using it still triggers a React re-render.
API Reference
👉 defineStorage
DefineStorageOptions
The options of the storage service.
Prop | Type | Default |
---|---|---|
deserialize? | ((value: string) => any) | - |
serialize? | ((value: unknown) => string) | - |
validate | TValidator | - |
key | string | - |
type | "local" | "session" | - |
👉 useStorage
Manage storage state like with useState.
👉 Storage
Read and write to the storage outside of React.