Files
botsmann/lib/hooks/useLocalStorage.ts
Mao NakamotoandClaude Opus 4.8 542d558f1f refactor(hooks): adopt eslint-plugin-react-hooks v6 rules (Next 16)
Re-enables the three React-Compiler-era rules deferred in #114
(set-state-in-effect, error-boundaries, immutability) — all now ON — and
resolves every violation with a real fix or a justified, documented exception.

error-boundaries (12 → 0, real fix):
- app/blog/[slug]/page.tsx wrapped its whole render in try/catch that only
  re-threw. Removed it: notFound()/render errors now propagate to Next's
  not-found.tsx / error.tsx as intended (the catch also mislogged notFound()).

immutability (5 → 0, real fix):
- The auth pages assigned window.location.href during render. Moved each
  redirect into a useEffect (above the early returns for rules-of-hooks),
  preserving the full-page navigation while keeping render pure.
  signin, signup, forgot-password, verify-email (×2).

set-state-in-effect (13 → 0, justified inline disables):
- Every case is a legitimate effect use — external-system sync (Supabase auth,
  API loads), browser-only hydration (localStorage, client-mount), or seeding
  editable state from async-loaded data. Forcing them off-effect would add
  complexity or risk behaviour changes to auth/data code, so each carries an
  eslint-disable-next-line with a specific reason. The rule stays ON to catch
  genuinely-avoidable derived-state-in-effect in future code.

Verified: eslint . (0 problems), prettier, tsc --noEmit, next build, jest 227 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-26 12:24:46 +02:00

33 lines
846 B
TypeScript

'use client';
import { useState, useEffect, useCallback } from 'react';
/**
* Hook for persisting boolean state in localStorage.
* SSR-safe: returns initialValue until hydration completes.
*/
export function useLocalStorageFlag(
key: string,
initialValue = false,
): [boolean, (value: boolean) => void] {
const [value, setValue] = useState(initialValue);
useEffect(() => {
const stored = localStorage.getItem(key);
if (stored !== null) {
// eslint-disable-next-line react-hooks/set-state-in-effect -- hydrates from localStorage after mount (SSR-safe by design)
setValue(stored === 'true');
}
}, [key]);
const setAndPersist = useCallback(
(newValue: boolean) => {
setValue(newValue);
localStorage.setItem(key, String(newValue));
},
[key],
);
return [value, setAndPersist];
}