useLocalStorageState
A Hook that store state into localStorage.
Overview
A Hook that store state into localStorage.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useLocalStorageState.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useLocalStorageState.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useLocalStorageState.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useLocalStorageState.jsonA Hook that store state into localStorage.
Examples
Store state into localStorage
Store complex types of data
Custom serialization and deserialization functions
Sync state with localStorage
API
If you want to delete this record from localStorage, you can use setState() or setState(undefined).
type SetState<S> = S | ((prevState?: S) => S);
interface Options<T> {
defaultValue?: T | (() => T);
listenStorageChange?: boolean;
serializer?: (value: T) => string;
deserializer?: (value: string) => T;
onError?: (error: unknown) => void;
}
const [state, setState] = useLocalStorageState<T>(
key: string,
options: Options<T>
): [T?, (value?: SetState<T>) => void];Result
| Property | Description | Type |
| -- | -- |
| defaultValue | Default value | any \| (() => any) | - |
| listenStorageChange | Whether to listen storage changes. If true, when the stored value changes, all useLocalStorageState with the same key will synchronize their states, including different tabs of the same browser | boolean | false |
| serializer | Custom serialization method | (value: any) => string | JSON.stringify |
| deserializer | Custom deserialization method | (value: string) => any | JSON.parse |
| onError | On error callback | (error: unknown) => void | (e) => { console.error(e) } |
Remark
useLocalStorageState will call serializer before write data to localStorage, and call deserializer once after read data.