React Hook Foundations Flashcards

Goal: instant recall of each hook/API's purpose, when to use it, and when NOT to use it. Format: atomic answers (~10s). Grouped by hook. (59 cards)

1
Q

Foundations: useState — what is it used for?

A

Adds local component state.
setState schedules the next render (state is a per-render snapshot).
Use for UI/local state (inputs, toggles, selection).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Foundations: useState — when NOT to use it?

A

Don’t store derived state (compute from props/state).
Complex transitions → useReducer.
Server data/caching → a cache layer (e.g., React Query).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Foundations: useState — top gotchas evaluators flag

A
  • Mutation: never modify objects/arrays in place.
  • Stale updates: use functional updates when next depends on prev.
  • Not immediate: don’t assume state changed right after setState.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Foundations: useState — canonical TS patterns

A

Type when needed: useState<T | null>(null).
Prev-based: setN(n => n + 1).
Lazy init: useState(() => expensiveInit()).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Foundations: useReducer — what is it used for?

A

State via a reducer: dispatch(action) computes next state.
Use for complex transitions / multiple related fields.
Improves predictability vs many useStates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Foundations: useReducer — when NOT to use it?

A

Don’t use for simple scalar UI state (prefer useState).
Don’t put async side effects in the reducer (keep reducer pure).
Server state still belongs in a cache layer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Foundations: useReducer — gotchas evaluators flag

A
  • Reducer must be pure (no mutation, no IO).
  • Unclear action types → hard to maintain.
  • Overloading one reducer for unrelated concerns.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Foundations: useReducer — canonical TS patterns

A

Prefer discriminated unions for actions.
Reducer signature: (state, action) => nextState.
Initialize with stable initialState (or init function if needed).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Foundations: useEffect — what is it used for?

A

Runs side effects after render.
Use to sync with external systems (fetch, subscriptions, timers).
Supports cleanup: return () => ....

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Foundations: useEffect — dependency array basics

A

[deps] must include reactive inputs used inside the effect.
Missing deps → stale closure bugs.
Cleanup runs on unmount and before re-run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Foundations: useEffect — when NOT to use it?

A

Don’t use effects to compute derived UI state.
Don’t mirror props into state unless you truly need it.
Don’t use effect as a general “run code” bucket (prefer event handlers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Foundations: useEffect — top gotchas evaluators flag

A
  • Race: older async result overwrites newer state.
  • setState-after-unmount: missing cleanup/abort.
  • Infinite loops: effect updates state that retriggers itself.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Foundations: useLayoutEffect — what is it used for?

A

Like useEffect, but runs before paint after DOM mutations.
Use for measure → write to avoid flicker.
Keep work minimal (can block paint).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Foundations: useLayoutEffect — when NOT to use it?

A

Prefer useEffect unless you need layout timing.
Avoid heavy work (jank).
Be careful with SSR (may warn if it runs on server).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Foundations: useLayoutEffect — common gotcha

A

Overuse causes render blocking / jank.
If you’re not measuring layout, it’s usually the wrong tool.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Foundations: useMemo — what is it used for?

A

Memoizes a computed value.
Recomputes only when deps change.
Use for expensive compute or stable derived objects/arrays.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Foundations: useMemo — when NOT to use it?

A

Don’t memoize trivial work (overhead > benefit).
Don’t use it as correctness glue for missing deps.
If nothing depends on reference identity, skip it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Foundations: useMemo — gotchas evaluators flag

A
  • Wrong deps → stale values.
  • Unstable deps: including an object/array literal created every render defeats memoization.
  • “Memo everywhere”: adds noise without measured benefit (prefer profiling evidence).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Foundations: useCallback — what is it used for?

A

Memoizes a function identity.
Use when passing callbacks to React.memo children or effect deps.
Helps with referential stability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Foundations: useCallback — when NOT to use it?

A

Don’t wrap every handler by default.
If the callback isn’t a dependency and not passed to memoized children, skip it.
Premature optimization can harm readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Foundations: useCallback — gotchas evaluators flag

A
  • Wrong deps → callback reads stale state/props.
  • Assuming it prevents rerenders by itself (it doesn’t).
  • Overuse increases cognitive load.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Foundations: useRef — what is it used for?

A

Persistent mutable container: ref.current survives renders.
Updating it does not rerender.
Use for DOM refs or instance values (timers, previous values).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Foundations: useRef — when NOT to use it?

A
  • If the UI must update when the value changes → use state.
  • If rendering depends on it, useRef can cause ghost UI (data changes, screen doesn’t).
  • Avoid heavy imperative DOM manipulation that fights React.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Foundations: useRef — gotchas evaluators flag

A
  • Using ref as state (UI doesn’t rerender).
  • Mutating ref during render in concurrency-sensitive flows.
  • Imperative DOM hacks that fight React reconciliation.
25
Foundations: useRef — canonical patterns
DOM ref: `const inputRef = useRef(null)`. Prev value: update `ref.current` in an effect. Timer id: store in ref; clear in cleanup.
26
Foundations: useContext — what is it used for?
Reads from nearest matching **Context Provider**. Use to share app-wide concerns (theme, auth, i18n) without prop drilling. Consumers rerender when provider value identity changes.
27
Foundations: useContext — when NOT to use it?
Don't put fast-changing/high-churn values in a top-level context. Don't use one giant context for unrelated values. Sometimes composition/props is simpler.
28
Foundations: useContext — gotchas evaluators flag
- Provider too high + hot value → **rerender flood**. - **Object literal trap:** `value={{ user }}` changes identity every render; stabilize with `useMemo` or pass primitives. - Missing provider guard → `null`/`undefined` context crashes.
29
Foundations: useTransition — what is it used for?
Marks updates as **non-urgent** to keep UI responsive. Gives `isPending` and `startTransition`. Use for expensive UI updates triggered by user input.
30
Foundations: useTransition — when NOT to use it?
Not a correctness fix. If the render isn't expensive, it adds complexity. Doesn't replace memoization/virtualization when needed.
31
Foundations: useTransition — gotchas evaluators flag
Using it to hide performance problems without addressing root cause. Forgetting to keep urgent updates outside the transition.
32
Foundations: useDeferredValue — what is it used for?
Provides a **deferred** version of a value. Urgent updates render first; deferred value lags. Use to keep inputs responsive while expensive results render.
33
Foundations: useDeferredValue — when NOT to use it?
It doesn't reduce compute cost by itself. If you need correctness/consistency, don't rely on deferred values. Not a substitute for caching.
34
Foundations: useDeferredValue — gotchas evaluators flag
Expecting it to fix slow renders without optimizing compute/render. Using it where stale results are unacceptable.
35
Foundations: useSyncExternalStore — what is it used for?
Subscribe to an **external store** safely under concurrent rendering. Prevents tearing by coordinating subscription + snapshot reads. Use for custom stores / external state containers.
36
Foundations: useSyncExternalStore — when NOT to use it?
Don't use for local component state. If you're using a library integration that already handles it, don't rewrap. Avoid ad-hoc subscribe hooks that ignore concurrency.
37
Foundations: useSyncExternalStore — gotchas evaluators flag
- **Snapshot caching trap:** if `getSnapshot` returns a new object each call, React can re-render indefinitely ("getSnapshot should be cached"). - Snapshot not stable/consistent → tearing. - Subscribe/unsubscribe bugs (leaks / missed updates).
38
Foundations: useActionState — what is it used for? (React 19)
Manages **action-driven state** for async mutations (often forms). Returns: **state + action dispatcher + pending** (conceptually). Use to avoid scattered `loading/error/result` state.
39
Foundations: useActionState — naming note (compat)
Formerly seen as `useFormState` in earlier canary/framework docs. Evaluator-safe phrasing: "`useActionState` (aka earlier `useFormState`)".
40
Foundations: useActionState — when NOT to use it?
Don't use for pure synchronous UI state. If a server-state library owns mutation state, avoid duplicating it. Don't cross client/server boundaries with secrets.
41
Foundations: useActionState — gotchas evaluators flag
- **Dispatch context trap:** calling the returned action outside a `
` / `button formAction` (or outside `startTransition`) can warn and pending tracking may not behave as intended. - Manual tri-state spaghetti instead of action-driven state. - Missing error/result handling from the action.
42
Foundations: useOptimistic — what is it used for?
Optimistic UI state: show expected result **before** server confirms. Use with mutations to keep UX snappy. Pair with rollback/invalidation on settle.
43
Foundations: useOptimistic — when NOT to use it?
- Don’t use if you can’t safely roll back. - **Prediction gap:** if the server must compute the next state (e.g., DB-generated IDs), optimistic state may be wrong. - Avoid when inconsistency is unacceptable.
44
Foundations: useOptimistic — gotchas evaluators flag
- No rollback/compensation on error. - Optimistic updates that diverge from server truth. - Forgetting to reconcile with refetch/invalidation.
45
Foundations: useId — what is it used for?
Generates **stable unique IDs** across server/client rendering. Use for a11y wiring: `label` ↔ `input` / `aria-describedby`. Helps avoid hydration mismatches for IDs.
46
Foundations: useId — when NOT to use it?
Not for list keys. Not for security tokens. If a stable id comes from data (DB id), use that instead.
47
Foundations: useImperativeHandle — what is it used for?
Customize the **ref API** a component exposes. Requires `forwardRef`. Expose small, intentional imperative methods (`focus`, `scrollTo`).
48
Foundations: useImperativeHandle — when NOT to use it?
Prefer declarative props/state when possible. Don't expose large surface areas or internal DOM details. Avoid unless consumers truly need imperative control.
49
Foundations: useImperativeHandle — gotchas evaluators flag
- Overusing imperative APIs increases coupling. - Exposing unstable methods/objects without memoization. - Using refs to work around poor component API design.
50
Foundations: useEffectEvent — what is it used for?
Creates a stable callback that can read the **latest** props/state without forcing effects to re-run for those values. Use to avoid stale closures in event-like logic.
51
Foundations: useEffectEvent — when to reach for it
- When an effect should re-run for **A**, but must read the latest **B** without making **B** a dependency. - Keeps deps focused on true triggers. - Reduces "dependency wars" and avoids accidental loops.
52
Foundations: useEffectEvent — gotchas evaluators flag
- Treating it like a general-purpose hook everywhere. - Forgetting normal hook rules still apply (top-level call). - Using it to hide architectural problems (over-coupled effects).
53
Foundations: useFormStatus — what is it used for? (react-dom)
Reads **form submission status** from the nearest `` context. Commonly used to disable submit buttons / show pending UI. Designed for actions-based form flows.
54
Foundations: useFormStatus — critical call-site rule
Must be called from a component **rendered inside** the ``. If called outside, `pending` won't reflect the form's status.
55
Foundations: useFormStatus — gotchas evaluators flag
- Calling it outside the form → `pending` always false. - Double-submit risk if pending isn't respected. - Confusing it with generic loading state.
56
Foundations: `use` (React API) — what is it?
`use(resource)` is a React **API** (not a Hook). It can read a **Promise** or **Context** and integrate with Suspense. Key distinction: different call-site rules vs Hooks.
57
Foundations: `use` — call-site rules (trap)
Hooks must be called **top-level**. `use(...)` can be called in **conditionals/loops**. Evaluator tell: don't call it "a hook".
58
Foundations: `use` — when to use it
When consuming a resource that may suspend (Promise) or a Context in places where Hook rules would be awkward. Use in environments that support Suspense-based data flows.
59
Foundations: `use` — gotchas evaluators flag
- **Boundary trap:** `use(promise)` suspends; you need a parent `` fallback (and an Error Boundary for rejections) for safe UX. - Don’t create Promises in Client Components on every render (unstable). - Avoid client/server boundary mistakes (secrets / non-serializable values).