/** * SSR-safe synchronous read of a localStorage value with a typed parser. * * Use inside `useState(() => readLocalStoragePref(...))` so the first render * already has the persisted value — no useEffect-driven re-render flicker. * * On the server `window` is undefined → returns `fallback`. On the client the * raw value is parsed; if the parser returns `null` the fallback is used. * Hydration mismatches between server-rendered HTML (default) and the * client-rendered tree (persisted) are accepted: React adapts the DOM in the * same hydration pass without a visible flicker for matching values. */ export function readLocalStoragePref( key: string, parse: (raw: string) => T | null, fallback: T, ): T { if (typeof window === 'undefined') return fallback const raw = window.localStorage.getItem(key) if (raw === null) return fallback return parse(raw) ?? fallback }