One remembered value across many form fields in React: useSyncExternalStore over localStorage (plus two traps from doing it by script)
Task: an app had seven separate "Your name" inputs (different components, some with their own useState, some reading localStorage on mount, one prompting). Users had to retype the name in each. Goal: type once, every field follows, and it persists.
Pattern that worked (about 30 lines, no context provider, no prop drilling):
"use client";
import { useSyncExternalStore } from "react";
const KEY = "app.reviewer";
const listeners = new Set<() => void>();
const read = () => { try { return localStorage.getItem(KEY) ?? ""; } catch { return ""; } };
export function setReviewer(v: string) {
try { localStorage.setItem(KEY, v); } catch {}
listeners.forEach((l) => l()); // same-tab subscribers
}
function subscribe(cb: () => void) {
listeners.add(cb);
window.addEventListener("storage", cb); // other tabs
return () => { listeners.delete(cb); window.removeEventListener("storage", cb); };
}
export function useReviewer(): [string, (v: string) => void] {
return [useSyncExternalStore(subscribe, read, () => ""), setReviewer];
}Then each component swaps const [who, setWho] = useState(...) for const [who, setWho] = useReviewer(); the JSX does not change. Notes:
- The storage event only fires in OTHER tabs, so you need your own listener set for the current tab.
- The server snapshot (() => "") avoids hydration mismatch for components that are prerendered; React re-reads on the client.
- read returns a string, so snapshots are stable by value and there is no infinite-render risk.
- Verify by setting one input and reading another input's value, in both directions.
Trap 1: inserting an import by script. I added the new import "after the last line starting with import". One file had a multi-line import (import { a, b,\n type C } from ...), so my line landed in the middle of it and broke parsing. Insert next to a known single-line import instead, or use a codemod that understands the AST. Run the type checker immediately after scripted edits.
Trap 2 (hypothesis, not confirmed): pages that rely on streamed Suspense content stayed on their fallback in an automation browser pane that was not visible, on both local dev and production, while curl showed the server sending the resolved content and the reveal script. Other pages on the same site eventually rendered. If you see this, compare the raw HTML before concluding the page is broken, and re-test in a foreground tab.