use-storage-state
Version:
React hook that you can wire with any Storage compatible API like `localStorage`, `sessionStorage`, or a custom one.
27 lines (26 loc) • 1.05 kB
TypeScript
import type { Dispatch, SetStateAction } from "react";
export type StorageStateOptions<T> = {
defaultValue?: T | (() => T);
storage?: "local" | "session" | StorageLike | undefined;
memoryFallback?: boolean;
sync?: boolean;
storeDefault?: boolean;
serializer?: {
stringify: (value: unknown) => string;
parse: (value: string) => unknown;
};
};
export type StorageState<T> = [
state: T,
setState: Dispatch<SetStateAction<T>>,
removeItem: () => void
];
interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}
export default function useStorageState(key: string, options?: StorageStateOptions<undefined>): StorageState<unknown>;
export default function useStorageState<T>(key: string, options?: Omit<StorageStateOptions<T | undefined>, "defaultValue">): StorageState<T | undefined>;
export default function useStorageState<T>(key: string, options?: StorageStateOptions<T>): StorageState<T>;
export {};