React Fundamentals Flashcards

(84 cards)

1
Q

Define: Render Purity (React).

A
  • Definition: Rendering must be a deterministic (pure) calculation of UI from props/state.
  • Requirement: Given the same inputs (Props, State, Context), a component must return the exact same JSX output without side effects.
  • Example of “impure”: calling fetch() or setState() during render breaks purity.
  • Senior Evaluator “Why”: Essential for Concurrent React. If rendering isn’t pure, React cannot safely pause or restart rendering without causing bugs.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

List 3 Categories of “Impure” Red Flags in React Render.

A
  • Red Flags (Impure Patterns):
    1. External Dependencies (The “Global Variable Trap”):
    Reading/writing variables defined outside the function or localStorage during render.
    2. Illegal Side Effects (The “Mutation & API Trap”):
    Performing actions that change the state of the “world” (e.g., fetch, setTimeout, setCount, or mutating props like props.data.push()).
    3. Non-Determinism (The “Randomness & Time Trap”):
    Using values that change every time the function is called (e.g., Math.random(), new Date(), or crypto.randomUUID()).
  • Correct Pattern: Move side effects to useEffect or event handlers.
  • Why it matters: Prevents infinite loops, “ghost” bugs in concurrent rendering, and UI/Data mismatches.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

React Purity “Red Flag”:

External Dependencies

(The “Global Variable Trap”)

A

Reading/writing variables defined outside the function or localStorage during render.

  • The Issue: React doesn’t track these; changes won’t trigger re-renders. Multiple component instances will “fight” over the same shared variable, causing non-deterministic UI.
  • Senior Tip: Look for variables declared above the component line (module scope) that get modified inside the render body.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

React Purity “Red Flag”:

Illegal Side Effects & Prop Mutation

(The “Mutation & API Trap”)

A

Performing actions that change the state of the “world” (e.g., fetch, setTimeout, or setCount) or mutating props directly.

  • The Issue: State updates during render trigger an immediate re-render, often leading to infinite loops.
  • Prop Mutation: Calling methods like props.items.sort(), props.items.reverse(), or props.data.push() is a critical error. These mutate the parent’s data in memory, breaking unidirectional data flow.
  • Senior Tip: If an AI needs to sort a prop, it must copy it first: [...props.items].sort().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

React Purity “Red Flag”:

Non-Determinism
(The “Randomness & Time Trap”)

A

Using values that change every time the function is called (e.g., Math.random(), new Date(), or crypto.randomUUID()).

  • The Issue: In Server-Side Rendering (SSR), the server and client generate different values. This causes a “Hydration Mismatch”—the HTML won’t match the JavaScript, causing UI flickers or broken interactivity.
  • Senior Tip: If you see key={Math.random()}, it’s a massive red flag for reconciliation performance and stability.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Define: reconciliation.

A

Definition: React’s “diffing” process to sync the Virtual DOM with the Real DOM.
* The Goal: To find the minimal set of changes needed to update the UI efficiently.
* The Heuristics:
1. Element Type: If the tag changes (e.g., <div> to <span>), React destroys the old tree and builds a new one.
2. Stable Keys: key props allow React to match items across renders, even if they move positions.
* Why it matters: Prevents expensive, full-page re-renders.

Additional info:

The Algorithm: Uses two main heuristics:
1. Different Types: If elements change from <div> to <span>, React destroys the old tree and builds a new one.
2. Keys: Stable, unique keys allow React to match items across renders, even if they’ve moved positions (crucial for lists).

  • Senior Tip: Reconciliation is the logic (calculating the diff), while Rendering is the action (calling component functions). They are separate phases!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Define: controlled component.

A

Definition: A form element (e.g., <input>, <select>) where the source of truth is React state, not the internal DOM state.

  • The Pattern:
    1. Value: value={state} (Forces the input to show the state).
    2. Change: onChange={e => setState(e.target.value)} (Updates state from user input).
  • The Goal: Gives React full control over the input for validation, formatting, or conditional disabling.
  • Contrast: Uncontrolled components store their own state in the DOM (accessed via ref).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Define: uncontrolled component.

A
  • Definition: input stores its own internal state; React reads via ref.
  • Use when: quick/simple forms or integrating non-React widgets.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Define: lifting state up.

A
  • Definition: moving shared state to the nearest common parent.
  • Benefit: single source of truth for multiple children.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Define: prop drilling.

A
  • Definition: passing props through intermediate components that do not use them.
  • Tradeoff: can be fine locally; use context when it becomes noisy.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define: referential equality.

A
  • Definition: two references point to the same object/function in memory.
  • Why it matters: React.memo/useMemo/useCallback depend on stable references.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Define: key (list rendering).

A
  • Definition: stable identifier that helps React match list items between renders.
  • Rule: use a stable unique id, not the array index for reorderable lists.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Define: derived state.

A
  • Definition: state that can be computed from props/state.
  • Risk: drift if stored separately.
  • Prefer: compute during render or memoize if expensive.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Define: batching (state updates).

A
  • Definition: React may batch multiple state updates into a single render.
  • Impact: reading stale state is common unless you use functional updates.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Define: functional state update.

A
  • Definition: setState(prev => next).
  • Use when: next state depends on previous state (especially in events/async).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Define: stale state bug (increment pattern).

A
  • Symptom: calling setN(n+1) twice results in +1, not +2.
  • Fix: setN(prev => prev + 1) for each update.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Define: strict mode double-invocation (dev).

A
  • In development, StrictMode may run certain lifecycles/effects twice to surface bugs.
  • Evaluator implication: code must be idempotent and safe under re-run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Define: state immutability.

A
  • Rule: never mutate state objects/arrays in place.
  • Why: React compares references; mutation can prevent updates or cause shared-state bugs.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Define: composition (React).

A
  • Definition: building UIs by combining components/children rather than inheritance.
  • Example: <Layout><Sidebar></Sidebar>...</Layout>.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Define: conditional rendering.

A
  • Patterns: ternary, &&, early return.
  • Best practice: keep conditions readable and deterministic.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Define: fragment.

A
  • Definition: group elements without extra DOM node.
  • Syntax: <>…</> or <React.Fragment>.</React.Fragment>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Define: React.memo (concept).

A
  • Definition: memoizes a component to skip renders when props are referentially equal.
  • Caveat: only helps when rerenders are frequent and render is expensive.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Define: Suspense (baseline).

A
  • Definition: lets a component wait and show a fallback while something suspends.
  • Evaluator note: do not treat Suspense as a generic error handler.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Define: Error Boundary (baseline).

A
  • Definition: component that catches render-time errors in its subtree.
  • Limitation: does not catch errors in event handlers or async callbacks.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Define: hydration mismatch (SSR).
- Definition: server-rendered HTML does not match client render. - Common causes: Date.now(), random, reading window during render.
26
Define: single source of truth.
- Definition: one authoritative place where a piece of data is stored. - Benefit: avoids drift and inconsistent UI.
27
Define: render vs effect.
- Render: compute UI. - Effect: synchronize with external systems (network, subscriptions, DOM).
28
Define: useRef vs useState (high level).
- useState: triggers re-render when changed. - useRef: holds mutable value without re-render. - Use ref for instance-like storage (timers, DOM nodes).
29
Define: accessible name (React/a11y).
- Definition: the label assistive tech uses for an element. - Example: button text or aria-label. - Testing tie-in: enables getByRole({ name: ... }).
30
Spot the bug: Why can this key choice be wrong for many lists? ``` const rows = items.map((item, i) => ( )); ```
- Issue: index key is unstable if items can reorder/insert/delete. - Impact: wrong row can keep the wrong state/DOM. - Fix: use a stable unique id: key={item.id}.
31
Spot the bug: Why might this increment be incorrect? ``` function IncTwice() { const [n, setN] = React.useState(0); const onClick = () => { setN(n + 1); setN(n + 1); }; return ; } ```
- Issue: both updates read the same stale n. - Impact: result is +1, not +2. - Fix: use functional updates: ``` setN(prev => prev + 1); setN(prev => prev + 1); ```
32
Spot the bug: What is wrong with mutating state directly? ``` const [user, setUser] = React.useState({ name: "A" }); user.name = "B"; setUser(user); ```
- Issue: state object mutated in place. - Impact: React may not detect change; shared mutation bugs. - Fix: create a new object: ``` setUser(prev => ({ ...prev, name: "B" })); ```
33
Spot the bug: Why can this render cause an infinite loop? ``` function Bad() { const [n, setN] = React.useState(0); setN(n + 1); return
{n}
; } ```
- Issue: calling setState during render. - Impact: infinite re-render loop. - Fix: update in an event handler or an effect gated by deps.
34
Spot the Bug: Why is calling fetch directly in the component body a critical error? ``` function View() { fetch("/api/data"); // Problem here return
Hi
; } ```
- **The Issue:** **Side effects in the "Render Path."** Rendering must be a "pure" calculation. - **The Impact (The "Crash"):** React can call your function **many times** (or even skip calls). If this fetch ever triggers a state update, you create an **infinite loop** that crashes the browser and spams your server. - **The Concept:** React assumes rendering is **idempotent** (calling it 10 times with the same props should change nothing and have no side effects). - **The Fix:** Use `useEffect` with an empty dependency array (for mount-only), or better, a data-fetching library like TanStack Query.
35
Spot the bug: Why can this throw at runtime? ``` return
{user.name.toUpperCase()}
; ```
- Issue: assumes user and user.name are always present. - Impact: runtime crash when user is null/undefined. - Fix: guard or render a fallback before accessing name.
36
Spot the bug: Why is this derived state risky? ``` function FullName({ first, last }) { const [full, setFull] = React.useState(first + " " + last); React.useEffect(() => setFull(first + " " + last), []); return
{full}
; } ```
- Issue: derived state duplicated + effect deps are wrong. - Impact: full name never updates when props change. - Fix: compute in render (or memoize): ``` const full = first + " " + last; ```
37
Spot the bug: Why is this input uncontrolled even though state exists? ``` const [value, setValue] = React.useState(""); return setValue(e.target.value)} />; ```
- Issue: defaultValue makes the input uncontrolled after initial render. - Impact: UI can diverge from state. - Fix: use value={value} for a controlled input.
38
Spot the bug: What is wrong with this checkbox wiring? ``` return ( setChecked(e.target.value)} /> ); ```
- Issue: checkbox uses checked/unchecked, not value. - Impact: state becomes incorrect. - Fix: use checked={checked} and e.target.checked.
39
Spot the bug: Why is this memoization stale? ``` const filtered = React.useMemo(() => items.filter(f), []); ```
- Issue: deps are incomplete. - Impact: filtered never updates when items/f changes. - Fix: include dependencies: [items, f].
40
Spot the bug: Why can this callback be stale? ``` const onSave = React.useCallback(() => api.save(value), []); ```
- Issue: deps are incomplete; callback captures stale value. - Impact: saves old value. - Fix: include dependencies or pass value explicitly.
41
Spot the bug: What is missing here? ``` React.useEffect(() => { const id = setInterval(() => setTick(t => t + 1), 1000); }, []); ```
- Issue: interval is never cleared. - Impact: memory leak and updates after unmount. - Fix: return cleanup: ``` return () => clearInterval(id); ```
42
Spot the bug: Why is this SSR-unfriendly? ``` return
{Date.now()}
; ```
- Issue: server and client values differ. - Impact: hydration mismatch. - Fix: compute time in an effect or render a placeholder.
43
Spot the bug: What is missing in this list? ``` return items.map(item =>
  • {item.label}
  • ); ```
    - Issue: missing key prop. - Impact: inefficient reconciliation; state/DOM mismatches. - Fix: add stable key:
  • ...
  • 44
    Spot the bug: Why might this cause accidental form submit? ``` return ; ```
    - Issue: inside a form, button defaults to type='submit'. - Impact: accidental submission. - Fix: set type='button' when not submitting.
    45
    Spot the bug: What is wrong with this update? ``` setItems(items.push(newItem)); ```
    - Issue: mutates array and uses push return value. - Impact: state becomes a number; mutation bugs. - Fix: setItems(prev => [...prev, newItem]).
    46
    Spot the bug: Why can this conditional className be problematic? ```
    ```
    - Issue: when false, className becomes false. - Impact: inconsistent DOM attribute. - Fix: use ternary: isActive ? 'active' : '' (or helper).
    47
    Spot the bug: What is wrong with this map? ``` return items.map(item => { }); ```
    - Issue: braces require an explicit return. - Impact: renders nothing. - Fix: use parentheses or add return.
    48
    Spot the bug: Why can this drop updates? ``` setItems([...items, newItem]); ```
    - Issue: items can be stale under batching/rapid calls. - Impact: dropped updates. - Fix: setItems(prev => [...prev, newItem]).
    49
    Spot the bug: Why is this label not wired? ``` ```
    - Issue: label is not associated with input. - Impact: poor accessibility. - Fix: use htmlFor/id or wrap input in label.
    50
    Spot the bug: Why can this expression render 0? ``` return items.length && ; ```
    - Issue: items.length can be 0 and 0 may render. - Fix: use items.length > 0 ? : null.
    51
    Spot the bug: Why is this event listener effect incomplete? ``` React.useEffect(() => { window.addEventListener('resize', onResize); }, []); ```
    - Issue: missing cleanup. - Impact: leak / duplicate handlers. - Fix: return cleanup removing the listener.
    52
    Spot the bug: Why does this effect use stale value? ``` React.useEffect(() => { doThing(value); }, []); ```
    - Issue: deps are empty but value can change. - Fix: include value in deps (or refactor).
    53
    Spot the bug: Why can this memoized child still re-render? ``` const Child = React.memo(function Child({ options }) { ... }); ; ```
    - Issue: options is a new object each render. - Fix: memoize options or pass primitives when needed.
    54
    Spot the bug: Why is this state mirroring a prop risky? ``` const [open, setOpen] = React.useState(props.open); return ; ```
    - Issue: prop changes will not update state. - Fix: make it controlled (use props.open) or sync explicitly.
    55
    Spot the bug: Why is this a common security FAIL? ``` return
    ; ```
    - Issue: XSS risk for untrusted html. - Fix: avoid raw HTML or sanitize strictly.
    56
    Spot the bug: Why is this useMemo wrong? ``` const x = React.useMemo(() => compute(a, b), [a]); ```
    - Issue: missing b in deps. - Fix: include b.
    57
    Spot the bug: Why can this guard be incomplete? ``` return
    {user && user.name.toUpperCase()}
    ; ```
    - Issue: user.name may be undefined. - Fix: guard name or use optional chaining with fallback.
    58
    Spot the bug: Why does this ref callback cause trouble? ```
    { refs.push(node); }} /> ```
    - Issue: ref callback changes each render and has side effects. - Fix: store deterministically with useRef and cleanup.
    59
    Spot the bug: Why is this expensive compute repeated? ``` const big = expensiveCompute(data); return ; ```
    - Issue: expensiveCompute runs every render. - Fix: useMemo if measured and deps are correct.
    60
    Spot the bug: Why is this UI ambiguous? ``` if (error) return null; if (!data) return null; return ; ```
    - Issue: multiple states render null. - Fix: render distinct loading/error/empty states.
    61
    Spot the bug: Why is this useRef misuse for UI? ``` const n = React.useRef(0); n.current++; return
    {n.current}
    ; ```
    - Issue: ref updates do not trigger renders; UI can desync. - Fix: use state for UI values; ref for non-UI mutable storage.
    62
    Spot the bug: Why does this effect run too often? ``` React.useEffect(() => { element.scrollIntoView(); }); ```
    - Issue: runs after every render. - Fix: add deps and gate behavior.
    63
    Spot the bug: Why is this checkbox read wrong? ``` onChange={e => setChecked(e.target.value)} ```
    - Issue: checkbox uses e.target.checked. - Fix: setChecked(e.target.checked).
    64
    Spot the bug: Why can this className become 'false'? ```
    ```
    - Issue: cond false yields false. - Fix: ternary or helper.
    65
    When should you use a functional state update (setX(prev => ...))?
    - When next state depends on previous state. - When updates can be batched or triggered rapidly. - When updating arrays/objects from prior state.
    66
    When is using index as a key acceptable?
    - Only when the list is static: no reordering/insertions/deletions and items have no local state that must stick to identity.
    67
    When should you lift state up vs use context?
    - Lift state up for local sharing among a few components. - Use context when many layers need the value and prop drilling becomes noisy.
    68
    When should you use useMemo/useCallback?
    - When there is measured performance impact OR to preserve referential equality for memoized children. - Only with correct deps; avoid as default.
    69
    How should you handle loading vs error vs empty states?
    - Make states explicit and distinct. - Avoid rendering null for multiple states. - Ensure UI communicates what is happening.
    70
    What is a safe approach to update objects/arrays in state?
    - Never mutate. - Arrays: prev => [...prev, x] / prev.filter(...) / prev.map(...) - Objects: prev => ({ ...prev, key: value })
    71
    What is the single source of truth approach for form state?
    - Keep the form value either in React state (controlled) or in the DOM (uncontrolled), not both. - Prefer controlled when you need validation/derived UI.
    72
    How do you avoid re-running effects unnecessarily?
    - Keep dependencies minimal but correct. - Move derived values inside the effect or compute them in render. - Do not depend on values that change every render unless needed.
    73
    What is the correct pattern to attach DOM event listeners in React?
    - Use effect with cleanup: ``` useEffect(() => { window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, [onResize]); ```
    74
    What is the recommended query style in tests for React components?
    - Prefer getByRole with accessible name. - Use findBy* for async UI. - Avoid getByTestId unless necessary.
    75
    How do you structure components for readability?
    - Keep render logic simple. - Extract complex logic into helpers/hooks. - Prefer composition and small focused components.
    76
    What is a safe way to build conditional className values?
    - Prefer a clear ternary or a helper rather than relying on falsey values as strings.
    77
    How do you avoid hydration mismatch in SSR environments?
    - Avoid non-deterministic values in render (Date.now/random). - Do not read window/document during render. - Compute client-only values in effects.
    78
    When do Error Boundaries help?
    - They catch render-time errors in the subtree. - They do not catch async errors or event handler errors.
    79
    When should you use a ref for DOM access?
    - For imperative DOM APIs (focus, scroll, measure). - Avoid ref writes as a replacement for state.
    80
    What is the simplest pattern to prevent accidental form submit from a button?
    - Set type='button' on buttons that are not meant to submit.
    81
    How should you handle expensive computations in render?
    - Start simple. - If expensive and rerenders are frequent, memoize with correct deps.
    82
    Why is returning 0 from a && conditional sometimes bad?
    - items.length && ... can produce 0. - Prefer explicit boolean check or ternary.
    83
    How do you keep list rendering stable?
    - Provide stable keys. - Avoid mutating the array in place. - Keep item identity consistent across renders.
    84
    What is a safe default for state that depends on props?
    - Prefer using props directly (controlled). - If storing derived state, implement an explicit sync strategy and document assumptions.