Title: React Hooks Advanced Patterns — LearnCoachAssist

Q: Why does useEffect run twice in dev?
A: Strict Mode mounts → unmounts → remounts to catch bugs from missing cleanups. Production runs effects once per mount.

Q: Common cause of infinite useEffect loop?
A: Updating state inside the effect with a dep that changes when state updates. Memoize the value or remove from deps if it doesn't need to trigger.

Q: How does useCallback help?
A: Returns the same function reference unless deps change — avoids re-rendering children that take it as a prop and use memo().

Q: useMemo vs useCallback?
A: useMemo(f, d): memoizes a value (the result of f()).
useCallback(f, d): memoizes the function itself. Equivalent to useMemo(() => f, d).

Q: useRef common uses?
A: Mutable container that doesn't trigger re-render: DOM nodes, timers, latest-value pattern, instance variables.

Q: Pattern to read 'latest' state without stale closures?
A: const ref = useRef(state);
useEffect(() => { ref.current = state; });
// use ref.current inside callbacks

Q: useReducer vs useState?
A: Use useReducer when next state depends on previous state, when state shape is complex, or when actions describe intent better than setters.

Q: Lift state up or use Context?
A: Lift up if 2-3 components share state. Context for app-wide state or theme/auth. Don't use Context for high-frequency updates — re-renders all consumers.

Q: Why Context can cause perf issues?
A: Every consumer re-renders when context value changes. Split contexts by domain, memoize value, or use selector libraries (useContextSelector).

Q: Custom hook naming rule?
A: Must start with use — React linter and DevTools rely on this.

Q: Rules of Hooks (two)?
A: 1) Call at the top level of a component or another hook — not inside loops/conditions.
2) Call from React functions only — components or other hooks.

Q: How to debounce a value with hooks?
A: function useDebounced(v, ms=300) {
  const [d, setD] = useState(v);
  useEffect(() => {
    const t = setTimeout(() => setD(v), ms);
    return () => clearTimeout(t);
  }, [v, ms]);
  return d;
}

Q: How to fetch data with cleanup against race conditions?
A: Track an abort flag in the effect; check it before calling setState; cleanup sets the flag to true.

Q: Why not call setState in render?
A: Causes infinite render loop. The exception is the 'derived state' pattern where you setState only if a prop changed; usually better solved with a key or memoization.

Q: Lazy initial state?
A: useState(() => expensive()) — runs only once on mount.

Q: Functional updater pattern?
A: setCount(c => c + 1) — avoids stale closure issues when multiple updates happen before re-render.

Q: useEffect dep array empty []?
A: Runs once on mount, cleanup on unmount.

Q: useEffect with no dep array?
A: Runs after every render. Almost never what you want.

Q: useLayoutEffect when?
A: When you need to read DOM measurements and apply changes synchronously before paint to avoid flicker.

Q: useImperativeHandle?
A: Customize the instance value exposed by ref when using forwardRef. Restrict surface area exposed to parent.

Q: forwardRef use case?
A: Pass a ref through a component to a child DOM node (e.g., custom input).

Q: React 19 'use' hook?
A: Reads a Promise or Context value — can be called conditionally in render; works with Suspense for async data.

Q: Why memoize a child with React.memo?
A: Skip re-render when props are referentially equal. Pair with useCallback/useMemo on parent for the prop references.

Q: When NOT to use memo()?
A: Tiny components, deps that always change, or when memo overhead > render cost. Profile before optimizing.

Q: Compound component pattern?
A: Parent provides Context; children read it via custom hook. Useful for accordions, tabs, menus where children need shared state.

Q: Render props vs hooks?
A: Hooks usually replace render props with cleaner code. Render props still useful when behavior needs to inject JSX (e.g., headless UI libs).

Q: Controlled vs uncontrolled input?
A: Controlled: value driven by state, onChange updates it.
Uncontrolled: DOM is source of truth; access via ref.

Q: Form library you might pair with hooks?
A: React Hook Form (uncontrolled by default + perf-friendly), Formik, or controlled patterns with useReducer.

Q: Custom hook for window size?
A: function useWindowSize() {
  const [s, setS] = useState({w:innerWidth, h:innerHeight});
  useEffect(() => {
    const h = () => setS({w:innerWidth, h:innerHeight});
    addEventListener('resize', h);
    return () => removeEventListener('resize', h);
  }, []);
  return s;
}

Q: Common stale-closure trap with setInterval?
A: Callback captures initial state. Fix with refs for latest value or use a hook like useInterval that updates the callback ref.

Q: Best way to share async state across components?
A: Server state libraries: TanStack Query, SWR, Apollo. They handle caching, deduping, refetch, retries.

Q: Pattern to delay reading from localStorage to avoid SSR mismatch?
A: Initialize with default, then on mount sync from localStorage in useEffect — avoids hydration mismatch.

Q: Optimistic update pattern?
A: setState locally, kick off mutation, on error revert state. Libraries (TanStack Query) provide onMutate / onError hooks.

Q: Selector pattern with Context?
A: Wrap context with a selector hook that compares the selected value to skip re-renders; use use-context-selector or Zustand.

Q: Best practice for cleanup in custom hooks?
A: Always return a cleanup function from useEffect; if your hook subscribes/timers/listens, ensure cleanup, otherwise you'll leak memory and double-fire on remount.

Q: What does useTransition return?
A: A tuple [isPending, startTransition] — wraps updates as low-priority to keep UI responsive.

Q: When to use useTransition?
A: When a state update would block the UI (e.g., filtering a large list) — keeps current screen interactive.

Q: What is useDeferredValue?
A: Returns a deferred copy of a value; React updates it after urgent work completes — for derived state in expensive children.

Q: useTransition vs useDeferredValue?
A: useTransition: wraps a setter; you control the trigger. useDeferredValue: wraps a value; React decides priority.

Q: What does useSyncExternalStore do?
A: Subscribes to an external store with concurrent-safe semantics — used by Redux, Zustand, etc.

Q: useSyncExternalStore signature?
A: useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?)

Q: What is useId?
A: Generates a unique, SSR-safe ID — for aria-* attributes pairing labels and inputs.

Q: What is useInsertionEffect?
A: Runs synchronously before DOM mutations — used by CSS-in-JS libraries to inject styles.

Q: What is useDebugValue?
A: Custom hook label shown in React DevTools — for library authors only.

Q: What is useFormStatus (React 19)?
A: Inside a
, gives status of the parent form submission — pending, data, method, action.

Q: What is useActionState (React 19)?
A: Manages state tied to an action (form submission) and returns updated state.

Q: What is useOptimistic?
A: React 19 hook for optimistic UI — shows a predicted state until the async action resolves.

Q: useOptimistic example use?
A: Display a chat message immediately while the POST is in flight; revert on error.

Q: What is the "use" hook (React 19)?
A: Reads a Promise or Context — works inside conditions/loops; Suspense surrounds for Promise reads.

Q: Difference: useContext vs use(Context)?
A: useContext must be top-level. use(Context) can be inside conditions but still inside a component.

Q: Cleanup function semantics in useEffect?
A: Runs before next effect of the same dep change and on unmount — always reverse what the effect did.

Q: Effect with dep [user]: when does cleanup run?
A: Before each re-run (when user changes) and on unmount.

Q: Effect that subscribes to a socket — pattern?
A: useEffect(() => {
  const sock = connect();
  return () => sock.close();
}, [url]);

Q: Why is async function not allowed as effect callback?
A: Effect must return cleanup or void; async returns a Promise. Define inner async function and call it.

Q: Stale closure example?
A: useEffect(() => {
  setInterval(() => console.log(count), 1000);
}, []); // always logs initial count

Q: Fix stale closure with ref?
A: Keep a ref updated each render: useEffect(() => { ref.current = count; }); read ref.current in callback.

Q: What is the "useEvent" RFC?
A: Proposed hook for a stable callback that always sees the latest state — partly available as useEffectEvent in canary.

Q: React 19 form action prop?
A: <form action={asyncFn}> — calls fn with FormData; pairs with useFormStatus inside child.

Q: What is a Server Component?
A: Renders on the server, ships no JS to the client — for non-interactive UI; can fetch data directly.

Q: Can a Server Component use hooks?
A: No — only Client Components use hooks. Server Components run once on the server.

Q: "use client" directive?
A: Marks a file as a Client Component — required to use hooks, event handlers, browser APIs.

Q: "use server" directive?
A: Marks a function (or file's functions) as a Server Action callable from client.

Q: Where can a Client Component import a Server Component?
A: Through the children prop (composition), not via direct import.

Q: Suspense boundary purpose?
A: Catches descendants that suspend (data fetch, lazy load), shows fallback until ready.

Q: Pattern: combine Suspense with lazy?
A: const Profile = lazy(() => import('./Profile'));
<Suspense fallback={<Spinner/>}>
  <Profile/>
</Suspense>

Q: What is ErrorBoundary?
A: A class component implementing componentDidCatch — wraps subtree to handle render errors gracefully.

Q: Functional ErrorBoundary?
A: Not built-in — use libraries like react-error-boundary, or wrap a class component.

Q: Hook to read previous value?
A: function usePrev<T>(v: T) {
  const ref = useRef<T>();
  useEffect(() => { ref.current = v; });
  return ref.current;
}

Q: Hook for mount tracking?
A: function useIsMounted() {
  const ref = useRef(false);
  useEffect(() => { ref.current = true; return () => { ref.current = false; }; }, []);
  return ref.current;
}

Q: Pattern for once-only effect?
A: const ran = useRef(false); useEffect(() => { if (ran.current) return; ran.current = true; /* ... */ }, []); — handles StrictMode double-mount.

Q: StrictMode double effect — solution?
A: Make effects idempotent and clean up properly; don't write logic that assumes single execution.

Q: useEffect vs useLayoutEffect timing?
A: useEffect: after paint (async). useLayoutEffect: before paint (sync, blocks render).

Q: When to choose useLayoutEffect?
A: DOM measurement + immediate style update; or to prevent flash of incorrect visual.

Q: Performance impact of useLayoutEffect?
A: Blocks paint — heavy work delays render. Use sparingly.

Q: Why prefer reducers for complex state?
A: Centralizes transitions, keeps actions explicit, easier to test in isolation.

Q: Reducer + Context for global state?
A: Create context with state + dispatch; consumers read both via separate hooks for split re-renders.

Q: Pattern: hook returning state and bound actions?
A: function useCounter(init=0) {
  const [n, setN] = useState(init);
  return { n, inc: () => setN(x => x+1), dec: () => setN(x => x-1) };
}

Q: useFetch basic skeleton?
A: const [data, setData] = useState();
const [err, setErr] = useState();
useEffect(() => {
  let off = false;
  fetch(url).then(r => r.json()).then(d => !off && setData(d), e => !off && setErr(e));
  return () => { off = true; };
}, [url]);

Q: Why useState updates may batch?
A: React 18+ batches updates inside event handlers, promises, timeouts, and native events for fewer renders.

Q: Force flush updates eagerly?
A: flushSync(() => setX(1)) — synchronous; bypasses batching. Use rarely.

Q: Pattern: derived state from props (avoid)?
A: Don't store derived values in state; compute during render or memoize. State copies become stale.

Q: When derived state from props IS okay?
A: When the prop is the initial value only — use as useState(propInit) and ignore subsequent prop changes.

Q: "Reset state on prop change" pattern?
A: Use a key prop on the component — unmount/remount is cleaner than synchronizing state.

Q: Memoize selector output with shallowEqual?
A: Selector libs (reselect, use-context-selector) compare result with shallowEqual to skip downstream renders.

Q: TanStack Query useQuery basics?
A: const {data, isLoading, error} = useQuery({queryKey:['users'], queryFn}) — caches by key, dedupes, retries.

Q: TanStack Query mutation pattern?
A: const m = useMutation({mutationFn, onSuccess: () => queryClient.invalidateQueries(['users'])});

Q: SWR equivalent of useQuery?
A: const {data, error, isLoading} = useSWR(key, fetcher)

Q: Hook for infinite scroll with TanStack Query?
A: useInfiniteQuery — returns fetchNextPage, hasNextPage, pages array.

Q: useDeferredValue for search input?
A: const deferredQ = useDeferredValue(q); then filter big list using deferredQ — input stays responsive.

Q: Pattern: cancel fetch on unmount?
A: Use AbortController: pass signal to fetch; abort in cleanup.

Q: Why arrow function in render causes re-renders downstream?
A: New function identity every render. Wrap with useCallback to stabilize.

Q: useMemo for expensive computation?
A: const sorted = useMemo(() => data.sort(...), [data]); — recomputes only when data changes.

Q: useMemo pitfall?
A: Memoization has cost; if deps change every render, you pay overhead for zero benefit. Profile first.

Q: React Compiler (Forget) impact on memoization?
A: Automatically memoizes — manual useMemo/useCallback often unnecessary once the compiler is in use.

Q: Reading state inside an event handler — stale?
A: No — handlers re-create each render with fresh closure, so they see current state.

Q: Reading state inside a setInterval — stale?
A: Yes — interval callback closes over initial state. Refresh via ref or recreate interval per state change.

Q: Custom hook for prev count via ref?
A: function usePrev(value) {
  const r = useRef();
  useEffect(() => { r.current = value; });
  return r.current;
}

Q: useReducer initial state lazy init?
A: useReducer(reducer, initArg, init) — 3rd arg is a function to compute initial from initArg lazily.

Q: useReducer typing in TS?
A: useReducer<Reducer<State, Action>>(reducer, initial)

Q: Discriminated union for actions?
A: type Action = {type:'inc'} | {type:'set'; value:number} — switch on type, full inference inside.

Q: Why pass dispatch through Context?
A: Dispatch is stable across renders, so consumers that only need to dispatch don't re-render on state changes.

Q: Split context for state and dispatch?
A: StateContext + DispatchContext — dispatchers consume only the latter to skip re-renders.

Q: Hook to subscribe to media query?
A: function useMediaQuery(q) {
  const [m, setM] = useState(() => matchMedia(q).matches);
  useEffect(() => {
    const mql = matchMedia(q);
    const fn = e => setM(e.matches);
    mql.addEventListener('change', fn);
    return () => mql.removeEventListener('change', fn);
  }, [q]);
  return m;
}

Q: Hook to detect online status?
A: useSyncExternalStore(s, () => navigator.onLine) with subscribe on online/offline events.

Q: Hook to lazy-load image?
A: IntersectionObserver in useEffect — observes ref, set state to load on intersect.

Q: useImperativeHandle anti-pattern?
A: Exposing internal state to parent — usually means you should lift state instead.

Q: forwardRef + useImperativeHandle pattern?
A: const Input = forwardRef((p, ref) => {
  const inner = useRef();
  useImperativeHandle(ref, () => ({ focus: () => inner.current.focus() }));
  return <input ref={inner}/>;
});

Q: Avoid forwardRef in React 19+?
A: Yes — refs are now regular props on function components.

Q: Stable callback that reads latest state?
A: useEffectEvent (canary) — or roll your own with ref + useCallback.

Q: Pattern for polling that pauses when tab hidden?
A: useEffect with setInterval; document.visibilitychange listener clears/resumes interval.

Q: Pattern for form draft autosave?
A: Debounced effect: useEffect on form state, setTimeout to save, cleanup to clear timeout — fires only after typing stops.

Q: Why useCallback alone doesn't prevent re-render?
A: Stable function isn't enough — receiving component must also be wrapped in React.memo or use the function in a useEffect dep.

Q: React.memo + props with object literal — issue?
A: Object literal is new identity each render → memo broken. Memoize the object with useMemo.

Q: React 19 ref callback cleanup?
A: Ref callbacks can return a cleanup function — runs on unmount or when ref changes.

Q: Render counter for debugging?
A: const r = useRef(0); r.current++; — log each render to spot extra ones.

Q: React DevTools Profiler — basics?
A: Records commits, shows render durations, why each rerendered — find expensive components and bad deps.

Q: Should you wrap every list item in memo?
A: No — only when item renders are expensive and props are stable. Otherwise overhead beats savings.

Q: react-window for big lists?
A: Virtualizes rows so DOM has only visible ones — massive memory and render savings.

Q: key prop best practice?
A: Stable, unique per item (id), not array index — index causes wrong state preservation when list reorders.

Q: Effect ordering rule?
A: Effects run in declaration order on mount; cleanup runs in reverse order on unmount.

Q: useEffect with object dep — pitfall?
A: Object reference changes each render — effect runs every time. Stringify or memoize the dep.

Q: Use ref to store interval id?
A: const id = useRef(); useEffect(() => { id.current = setInterval(...); return () => clearInterval(id.current); }, []);

Q: "Single source of truth" with controlled inputs?
A: Parent owns state, child takes value + onChange — predictable but more boilerplate.

Q: Pattern for controlled + default value?
A: value={value ?? defaultValue} — falls back when uncontrolled.

Q: Pattern: useToggle?
A: function useToggle(init=false){ const [v,setV] = useState(init); return [v, () => setV(x=>!x)] as const; }

Q: Pattern: useClipboard?
A: useState for last-copied + async navigator.clipboard.writeText — return [copy, copied].

Q: Pattern: useHover?
A: useRef to element + onMouseEnter/onMouseLeave handlers maintaining state.

Q: useScript hook?
A: Appends <script> tag in useEffect; tracks loaded/error; cleans up on unmount or rerun.

Q: useOnClickOutside?
A: Listen on document mousedown; if event.target outside the ref's element, fire callback.

Q: useKeyboard?
A: Document keydown listener filtered by key — for keyboard shortcuts.

Q: useRouter (Next.js) — when to use?
A: Read query, push routes, listen to navigation events — pages/router only in app router context.

Q: Why hooks fail outside components?
A: React tracks calls by component instance; outside, no context — hook order can't be reconciled.

Q: "Conditional hook" violation example?
A: if (x) useState(0); — different number of hook calls per render breaks reconciliation.

Q: "Hooks fired in different order" warning?
A: Same root cause — hook order must be identical across renders. Always run hooks unconditionally; gate behavior inside.

Q: Conditionally render JSX, not hooks?
A: Hooks always run; conditional logic happens inside hooks or in returned JSX.

Q: Pattern: lazy state from localStorage?
A: const [v, setV] = useState(() => JSON.parse(localStorage.getItem(k) ?? 'null'));

Q: Pattern: persist state to localStorage?
A: useEffect(() => { localStorage.setItem(k, JSON.stringify(v)); }, [k, v]);

Q: Pattern: useLocalStorage hook?
A: Combines lazy init + effect to persist; handle JSON parse errors and SSR safety.

Q: SSR-safe localStorage access?
A: Guard with typeof window !== 'undefined' or use lazy init in useEffect to run only after mount.

Q: Hydration mismatch warning — common cause?
A: Server-rendered HTML differs from client first render. Avoid conditional UI based on browser-only data on initial render.

Q: suppressHydrationWarning use case?
A: Timestamp display that differs slightly between server and client; suppress on that element.

Q: useId for SSR?
A: Stable IDs across server and client; needed for aria associations to survive hydration.

Q: Use hooks in a non-component (utility)?
A: No — convert to a hook (use- prefix) or refactor to plain JS that takes state as args.

Q: Custom hook returning a stable callback?
A: const stable = useCallback(fn, []); + useRef for latest state — gives event-like stable function.

Q: useEffect dependency lint rule?
A: react-hooks/exhaustive-deps — flags missing deps; respect it or document why intentionally omitted.

Q: Disable exhaustive-deps for one line?
A: // eslint-disable-next-line react-hooks/exhaustive-deps with a comment explaining why.

Q: React Compiler vs manual useMemo?
A: Compiler auto-memoizes safe code; manual useMemo often becomes redundant. Profile to compare.

Q: Server Actions: how called?
A: Pass to action prop of form, or call directly from client; React handles RPC + revalidation.

Q: Server Actions revalidate path?
A: import { revalidatePath } from 'next/cache'; revalidatePath('/items') inside action.

Q: Server Actions revalidate tag?
A: revalidateTag('items') — invalidates fetches tagged with 'items'.

Q: useFormState (renamed useActionState in 19)?
A: Wraps action + initial state; returns [state, dispatchAction] — useful for form result with progressive enhancement.

Q: Pattern for optimistic delete?
A: const [optimistic, addOpt] = useOptimistic(items, (cur, id) => cur.filter(i => i.id !== id))

Q: React 19 ref as prop, not via forwardRef?
A: Just function Input({ ref }) — function components accept ref directly.

Q: RefObject vs MutableRefObject?
A: RefObject: {current: T | null}, set by React. MutableRefObject: {current: T}, you manage.

Q: Passing a callback as ref?
A: ref={(node) => { /* access node */ }} — runs when attached and detached (cleanup via returned fn in React 19).

Q: useImperativeHandle dep array?
A: Treats like useEffect — runs only when deps change.

Q: Hook to detect document focus?
A: useSyncExternalStore subscribed to 'visibilitychange' returning !document.hidden.

Q: useEffect for analytics on route change?
A: Effect on pathname dep, fires pageview each navigation; consider debouncing or single-instance ref.

Q: useEffect to set page title?
A: useEffect(() => { const prev = document.title; document.title = t; return () => { document.title = prev; }; }, [t]);

Q: Pattern for portal target ref?
A: Create ref to mount node, useEffect to call createPortal on a child once ref is set.

Q: React.lazy with named export?
A: const X = lazy(() => import('./X').then(m => ({default: m.X})));

Q: Pattern for retry on lazy error?
A: Wrap in try/catch and retry with backoff; or use error boundary that triggers a re-render.

Q: useEffect cleanup running unexpectedly?
A: StrictMode in dev — React mounts twice intentionally. Make sure cleanup is idempotent.

Q: Why does setState in render cause loop?
A: State update triggers re-render → render fires setState again → infinite. Use derived value in render or move to effect.

Q: Set state from inside effect of same state?
A: Fine if guarded by a condition that becomes false — otherwise infinite. Always have an exit condition.

Q: Effect dep that should fire only on mount?
A: Empty deps [] — but rules of hooks lint may warn; add explanatory comment.

Q: Disabling exhaustive-deps for an effect intentionally?
A: Add comment + lint disable; better is to extract the offending value into a useCallback or restructure.

Q: Hook to abort async on dep change?
A: Pattern: AbortController in ref; cleanup aborts; start new request after.

Q: Race condition with effect updating state?
A: Two effects in flight; the slower writes stale data. Track latest request id in ref, ignore older responses.

Q: Pattern: useEffect for keyboard shortcuts?
A: Effect adds keydown listener filtered by key + modifier; cleanup removes it; deps include handler dependencies via useCallback.

Q: React 19 form action + redirect?
A: Inside Server Action: import { redirect } from 'next/navigation'; redirect('/done');

Q: useFormStatus only inside form?
A: Yes — must be a descendant of the form whose status you want. Otherwise returns defaults.

Q: Conditional rendering best practice?
A: {condition && <X/>} for truthy gate; {cond ? <X/> : null} when you might add an else later.

Q: Avoid 0 rendering in conditional?
A: {count > 0 && <X/>} — `0 && ...` renders the 0. Coerce with !!count or compare explicitly.

Q: useDeferredValue with React 19 cache?
A: Combine for showing previous data while loading new — UI stays responsive during refetch.

Q: Why useEffect doesn't suspend?
A: Effects run after paint — suspense only catches sync render throws of promises. Use server components / data libs for suspense-aware data.

Q: Hook for window size with throttle?
A: Use raf or lodash throttle around handler; cleanup ensures it stops on unmount.

Q: Cancel a hot reload reset of state — strategy?
A: State that should persist across HMR — move to a store (Zustand, Redux) so it survives re-mounts.

Q: Pattern: keep WebSocket connection across tab visibility?
A: useSyncExternalStore subscribed to a singleton; useEffect doesn't recreate per render.

Q: Singleton hook pattern?
A: Create the store outside the component; hook only reads/subscribes to it.

Q: Zustand store basics?
A: const useStore = create((set) => ({ count: 0, inc: () => set(s => ({count: s.count+1})) }));

Q: Consume Zustand slice?
A: const count = useStore(s => s.count); — re-renders only when slice changes.

Q: Jotai atom basics?
A: const countAtom = atom(0); const [c, setC] = useAtom(countAtom); — primitive atoms compose into derived atoms.

Q: Recoil vs Zustand?
A: Both global state libs; Recoil from FB (dormant); Zustand simpler API, very popular.

Q: Redux Toolkit hook?
A: useSelector reads, useDispatch writes; createSlice replaces boilerplate.

Q: useReducer + Context performance issue?
A: All consumers re-render on any change. Split contexts or use selector libraries.

Q: react-redux performance pattern?
A: Use useSelector with shallowEqual or specific slices; never select root state.

Q: What is `flushSync`?
A: Sync flush of updates inside callback — useful before reading layout that depends on state.

Q: What is `startTransition` (non-hook)?
A: Wraps low-priority updates from outside components (e.g., event handler outside render tree).

Q: What is `unstable_batchedUpdates`?
A: Pre-18 API; React 18+ batches automatically across all sources.

Q: Concurrent rendering safety in hooks?
A: Pure renders only; don't mutate refs or external state in render. Side effects go in useEffect.

Q: Render-phase logic that's safe?
A: Computing derived values, calling pure functions, reading state — no I/O, no DOM, no subscriptions.

Q: Why React calls render twice in dev sometimes?
A: StrictMode invokes render twice to surface non-pure render side effects.

Q: "Cannot update a component while rendering a different component" warning?
A: Setting state of another component during render — defer to useEffect.

Q: Custom hook for fetch with retry?
A: Combine setTimeout backoff + AbortController + state machine (idle/loading/success/error/retry).

Q: Implement debounce in a hook?
A: function useDebounced<T>(v: T, ms=300) {
  const [d, setD] = useState(v);
  useEffect(() => {
    const t = setTimeout(() => setD(v), ms);
    return () => clearTimeout(t);
  }, [v, ms]);
  return d;
}

Q: Implement throttle in a hook?
A: useRef stores last timestamp; only update state if enough elapsed; trailing call via setTimeout.

Q: Pattern for one-shot effect on click outside?
A: Once handler fires, useEffect cleanup removes listener; setState to dismiss the popup.

Q: Pattern: useReducer with Immer?
A: const [s, d] = useReducer(produce(draft, action => { /* mutate draft */ }), init); — ergonomic immutable updates.

Q: Pattern: typed dispatch with discriminated union?
A: Action union type ensures payload matches type — full inference in reducer.

Q: React 19 cache() function?
A: Memoizes function calls per request — for Server Components, dedupes data fetches.

Q: React 19 use server actions error handling?
A: Throw inside action → caught by nearest error boundary (or returned via useActionState).

Q: Avoid useEffect for synced state?
A: Often computed in render or derived from props is correct; effects sync to external systems only.

Q: "You might not need an effect" (React docs)?
A: Common misuses: derived state, event handlers, expensive computations — all better outside useEffect.

Q: Hook to read URL params?
A: React Router: useParams, useSearchParams; Next.js app router: useParams, useSearchParams.

Q: Hook to navigate programmatically?
A: React Router: useNavigate; Next.js: useRouter (.push).

Q: Custom hook for query param state?
A: Read with useSearchParams, write with router.replace; encode/decode JSON if storing structured state.

Q: Pattern: useEffect doing analytics events on prop change?
A: useEffect(() => { track('view', {id}); }, [id]) — fires on each id change; cleanup if appropriate.

Q: Pattern: combine multiple refs?
A: function mergeRefs(...refs){ return (node) => refs.forEach(r => { if(typeof r === 'function') r(node); else if(r) r.current = node; }); }

Q: useId in lists — caveat?
A: useId generates ONE id per call site, not per item. Use useId once + suffix per item.

Q: Hook returning event handlers with stable identity?
A: Combine useCallback + useRef pattern; or wait for useEffectEvent stabilization.

Q: React 19 form action returning ServerAction result?
A: Form children can read via useFormStatus (in-flight) and useActionState (result).

Q: Server Component fetching with cache?
A: fetch(url, {next: {revalidate: 60}}) — Next.js caches for 60 seconds.

Q: Stale-while-revalidate with hooks?
A: TanStack Query + staleTime + background refetch — shows cached then updates.

Q: Pattern: useEffect with cleanup dep tracking?
A: If cleanup needs prev value, capture in ref before changing.

Q: useEffect double-fire mitigation in StrictMode?
A: Make effects idempotent: check before subscribing, debounce expensive setup, use AbortController on fetches.

Q: React 19 useFormStatus inside child component?
A: Yes — works in any descendant of the form. Returns pending, data, method, action.

Q: Hook to detect viewport scroll position?
A: useEffect adds scroll listener; useRef rAF to throttle; state updates infrequently.

Q: Best practice: list of memoized rows?
A: Memoize row component; pass stable callbacks via useCallback; key by stable id.

Q: Common mistake: using array index as key during reorder?
A: State binds to position, not item — wrong state persists when reorder happens.

Q: Why don't all libraries use useSyncExternalStore?
A: Older APIs (useEffect + setState) still work; new external stores should use it for concurrent safety.

Q: useSyncExternalStore SSR?
A: 3rd arg is `getServerSnapshot` for hydration; required for SSR.

Q: Common mistake: heavy useState init?
A: useState(expensive()) runs every render. Use useState(() => expensive()) to defer.

Q: Hooks vs HOCs vs render props — modern preference?
A: Hooks first, HOCs second, render props rarely. Hooks compose better and have stable APIs.