@typed-storage/react
v0.4.0
Published
   to build better apps.
Usage
Two steps: define your schema and use the hook, nothing else.
- Define your schema
// schema.ts
import { defineStorage } from "@typed-storage/react"
// Feel free to use any other StandardSchema compatible library
import { z } from "zod"
const { useStorage, storage } = defineStorage({
theme: z.enum(["light", "dark"]),
})
export { useStorage, storage }- Use the hook
// my-component.tsx
import { useStorage } from "./schema"
export function MyComponent() {
const [theme, setTheme] = useStorage("theme")
return (
<>
<div>{theme}</div>
<button onClick={() => setTheme("light")}>Light</button>
<button onClick={() => setTheme("dark")}>Dark</button>
{/* type-error: Cannot assign "system" to "light" | "dark" */}
<button onClick={() => setTheme("system")}>System</button>
</>
)
}Fallback values
You can define a fallback value for the key if it doesn't exist in the storage.
export function MyComponent() {
const [theme, setTheme] = useStorage("theme", "light")
return (
<>
{/* This will be "light" because the key doesn't exist in the storage */}
<div>{theme}</div>
</>
)
}Outside of React
To a type-safe way to access localStorage outside of React,
you can use the storage property that is returned
by the defineStorage function.
import { storage } from "./schema"
storage.set("theme", "light")
const theme = storage.get("theme")Installation
You can install this package with any package manager you like.
pnpm add @typed-storage/reactFeedback and Contributing
I highly appreceate your feedback! Please create an issue, if you've found any bugs or want to request a feature.
