@arolariu/components
Version:
🎨 70+ beautiful, accessible React components built on Base UI. TypeScript-first, CSS Modules styling, tree-shakeable, SSR-ready. Perfect for modern web apps, design systems & rapid prototyping. Zero config, maximum flexibility! ⚡
50 lines • 1.85 kB
TypeScript
/**
* Persists state to localStorage with SSR safety and JSON serialization.
*
* @remarks
* This hook synchronizes state with localStorage, allowing data to persist
* across page refreshes and browser sessions. It is SSR-safe and returns the
* initial value on the server until hydration completes. The hook also syncs
* state across tabs/windows via the `storage` event.
*
* Error handling:
* - On initial load, a JSON parse failure falls back to `initialValue`.
* - On a cross-tab `storage` event with malformed JSON, the event is ignored
* and the current local state is preserved (to avoid wiping user state on a
* bad cross-tab message).
* - `localStorage` write failures (quota exceeded, private-mode restrictions)
* are swallowed silently — the in-memory state update still succeeds.
*
* @typeParam T - The type of the value being stored.
* @param key - The localStorage key to store the value under.
* @param initialValue - The default value to use if no value is found in localStorage.
* @returns A tuple containing the current value and a setter function.
*
* @example
* ```tsx
* function UserSettings() {
* const [theme, setTheme] = useLocalStorage("theme", "light");
*
* return (
* <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
* Toggle theme (current: {theme})
* </button>
* );
* }
* ```
*
* @example
* ```tsx
* function ShoppingCart() {
* const [cart, setCart] = useLocalStorage<Product[]>("cart", []);
*
* return (
* <button onClick={() => setCart((prev) => [...prev, newProduct])}>
* Add to cart ({cart.length} items)
* </button>
* );
* }
* ```
*/
export declare function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((prev: T) => T)) => void];
//# sourceMappingURL=useLocalStorage.d.ts.map