pencils ready ✎

React MCQs multiple-choice questions with answers & explanations

All 226 React quiz questions on one page. Pick an answer in your head, then open Show answer to check it and read why. Want a score and a timer? Take them as a quiz instead.

Browse 25 study areas · 250 additional questions

Choose a focused set of questions. Coverage includes modern APIs, practical scenarios and maintenance of older applications; check version requirements for your project.

226 questions
  1. 1.

    Why can count && <Badge /> display a zero when count is zero?

    easy
    1. AThe expression returns the number zero
    2. BReact converts every false value to text
    3. CBadge is mounted with a zero prop
    Show answer

    Answer: A (The expression returns the number zero)

    JavaScript returns the left operand when falsy; React renders numbers, including zero. Use an explicit boolean condition.

  2. 2.

    Why does <profile /> not call an imported function named profile?

    easy
    1. AImports cannot be used in JSX
    2. BAll components must be classes
    3. CLowercase JSX names are treated as host element names
    Show answer

    Answer: C (Lowercase JSX names are treated as host element names)

    Use a capitalized component identifier so the JSX transform references the function rather than a host tag string.

  3. 3.

    A mapped item returns two sibling elements. Where should its stable key go?

    easy
    1. AOn the array variable
    2. BOn an explicit Fragment wrapping the pair
    3. COnly on the first nested element
    Show answer

    Answer: B (On an explicit Fragment wrapping the pair)

    The key belongs on the element directly returned by the mapping operation. Fragment shorthand cannot receive a key.

  4. 4.

    In <Button {...defaults} disabled={false} />, which disabled value wins?

    mid
    1. AThe explicit false value
    2. BThe value in defaults
    3. CBoth values are combined
    Show answer

    Answer: A (The explicit false value)

    Later JSX props override earlier properties with the same name, including properties supplied by a spread.

  5. 5.

    A layout accepts a toolbar element as a prop. What pattern does this illustrate?

    easy
    1. AInheritance of DOM nodes
    2. BMutating a child component
    3. CComposition through a slot
    Show answer

    Answer: C (Composition through a slot)

    Passing elements lets callers supply content without requiring the layout to know each toolbar implementation.

  6. 6.

    What should you do before rendering a plain user object as visible JSX content?

    easy
    1. AAdd a key to the object
    2. BSelect its display fields or format it
    3. CPass the object directly as a child
    Show answer

    Answer: B (Select its display fields or format it)

    Plain objects are not valid rendered children. Render a field such as user.name or explicitly serialize diagnostic output.

  7. 7.

    A component returns null. What happens to its existing component state while it stays mounted?

    easy
    1. AThe state can remain even though it renders no DOM
    2. BIts state is necessarily deleted
    3. CIt becomes a server component
    Show answer

    Answer: A (The state can remain even though it renders no DOM)

    Returning null removes visible output, not necessarily the component instance. Removing the component from its parent resets its state.

  8. 8.

    Why prefer <Panel /> to calling Panel() inside another component?

    mid
    1. ADirect calls always compile faster
    2. BJSX disables Hooks inside Panel
    3. CReact can track Panel as a separate component boundary
    Show answer

    Answer: C (React can track Panel as a separate component boundary)

    Direct function calls bypass component boundaries and can merge Hook execution into the caller, breaking the intended lifecycle structure.

  9. 9.

    After calling a state setter, why does the current handler still read its old state variable?

    easy
    1. AThe setter did not run
    2. BReact rewrites the variable only after console.log
    3. CThe handler belongs to the current render snapshot
    Show answer

    Answer: C (The handler belongs to the current render snapshot)

    A setter queues another render; it does not mutate the lexical variable captured by the current handler.

  10. 10.

    Starting at zero, two setCount(c => c + 1) calls in one handler produce what next count?

    easy
    1. A0
    2. B2
    3. C1
    Show answer

    Answer: B (2)

    Functional updaters are queued and each receives the result of the preceding update.

  11. 11.

    What does setUser({name: 'Mira'}) do to other fields in an object state value?

    easy
    1. AReplaces the whole value unless fields are explicitly preserved
    2. BShallow-merges all old fields automatically
    3. CDeletes the component
    Show answer

    Answer: A (Replaces the whole value unless fields are explicitly preserved)

    Hook setters replace state values. Spread existing fields when a partial object change should preserve them.

  12. 12.

    Which form defers an expensive state initializer until initialization?

    mid
    1. AuseState(createInitialState())
    2. BuseState(() => createInitialState)
    3. CuseState(createInitialState)
    Show answer

    Answer: C (useState(createInitialState))

    Passing the initializer function avoids evaluating it on every render. It must be pure because development checks may invoke it again.

  13. 13.

    A profile editor should discard its draft when the selected user changes. Which approach provides an explicit reset boundary?

    mid
    1. AMutate the existing draft object
    2. BKey the editor by the user ID
    3. CUse a random key on every render
    Show answer

    Answer: B (Key the editor by the user ID)

    A stable key per user preserves edits for that identity until the key changes; random keys reset on unrelated renders.

  14. 14.

    How should you sort an array stored in state without mutating it?

    easy
    1. ASort a copy and set the new array
    2. BCall sort on the existing state array
    3. CChange only its length property
    Show answer

    Answer: A (Sort a copy and set the new array)

    Array sort mutates its receiver. Copy first or use an immutable sorting operation supported by the runtime.

  15. 15.

    A total can be calculated cheaply from cart items. Where should it usually live?

    easy
    1. AAs duplicate state synchronized by an Effect
    2. BIn a module-level mutable variable
    3. CAs a calculation during render
    Show answer

    Answer: C (As a calculation during render)

    Deriving the total removes synchronization bugs and unnecessary state updates. Memoize only if profiling justifies it.

  16. 16.

    Setting state to the same object reference can skip an update because React compares values using what?

    mid
    1. AOnly their constructor names
    2. BObject.is semantics
    3. CDeep JSON equality
    Show answer

    Answer: B (Object.is semantics)

    Mutating an object and reusing its reference does not express a new value to React's state comparison.

  17. 17.

    Which button prop waits for a click before saving?

    easy
    1. AonClick={new save()}
    2. BonClick={save}
    3. ConClick={save()}
    Show answer

    Answer: B (onClick={save})

    Pass a function to an event prop. Calling it during render performs the work immediately.

  18. 18.

    In a bubbling handler, which property identifies the element whose handler is running?

    easy
    1. AcurrentTarget
    2. Btarget
    3. CrelatedTarget
    Show answer

    Answer: A (currentTarget)

    target can be a nested element that originated the event; currentTarget identifies the element handling it.

  19. 19.

    What prevents a normal form submission from navigating the page?

    easy
    1. ACalling stopPropagation only
    2. BReturning a string from the handler
    3. CCalling preventDefault on the submit event
    Show answer

    Answer: C (Calling preventDefault on the submit event)

    preventDefault cancels the browser's default action. Propagation control is a different concern.

  20. 20.

    Which property should update boolean state for a controlled checkbox?

    easy
    1. Aevent.target.name
    2. Bevent.target.checked
    3. Cevent.target.value only
    Show answer

    Answer: B (event.target.checked)

    checked represents the checkbox's boolean state; value is a separate submitted value.

  21. 21.

    An input starts with undefined value and later receives a string. What is the likely issue?

    mid
    1. AIt switches from uncontrolled to controlled
    2. BIt automatically becomes read-only forever
    3. CIt is forced to remount by its type
    Show answer

    Answer: A (It switches from uncontrolled to controlled)

    Initialize a controlled text value consistently, often with an empty string, to avoid switching ownership modes.

  22. 22.

    Why might a numeric field keep its editing value as a string?

    mid
    1. AReact cannot render numbers
    2. BString state disables validation
    3. CIntermediate input such as an empty field must be representable
    Show answer

    Answer: C (Intermediate input such as an empty field must be representable)

    Editing states do not always form valid numbers. Parse and validate at a deliberate boundary.

  23. 23.

    How should a file picker normally obtain the user's selected files?

    easy
    1. ARender file bytes inside its value prop
    2. BRead its FileList after user selection
    3. CSet its value to a local filesystem path
    Show answer

    Answer: B (Read its FileList after user selection)

    Browsers control file selection for security. Read the selected files and validate them on the server as well.

  24. 24.

    Which React prop observes a click in the capture phase?

    mid
    1. AonClickCapture
    2. BonClickBefore
    3. ConCaptureClick
    Show answer

    Answer: A (onClickCapture)

    Capture handlers run on the path toward the target before the usual bubbling handlers.

  25. 25.

    An Effect dependency changes. What happens to its previous cleanup?

    mid
    1. AIt runs before the replacement setup
    2. BIt runs only when the browser closes
    3. CIt runs before the component's first render
    Show answer

    Answer: A (It runs before the replacement setup)

    React cleans up the previous synchronization before establishing the next one, and also cleans up on unmount.

  26. 26.

    An Effect depends on a new options object made every render. Why might it reconnect too often?

    mid
    1. AReact compares every nested field deeply
    2. BObjects cannot be Effect dependencies
    3. CThe object has a new reference each render
    Show answer

    Answer: C (The object has a new reference each render)

    Construct the object inside the Effect or otherwise remove unnecessary reference churn without hiding real reactive dependencies.

  27. 27.

    Where should a purchase request caused by a button click normally begin?

    easy
    1. AIn a useMemo calculation
    2. BIn the interaction handler or action
    3. CIn a mount Effect merely because the page renders
    Show answer

    Answer: B (In the interaction handler or action)

    A purchase is caused by an explicit interaction, not by rendering. Effects synchronize with external systems and may restart.

  28. 28.

    Why should an Effect callback not directly be an async function?

    mid
    1. AIt returns a Promise instead of a cleanup function or nothing
    2. BAsync code is banned in components
    3. CPromises always block rendering
    Show answer

    Answer: A (It returns a Promise instead of a cleanup function or nothing)

    Define and invoke asynchronous work inside the Effect, and return synchronous cleanup when needed.

  29. 29.

    Two searches finish out of order. What prevents an old response replacing the latest result?

    mid
    1. AAlways accept whichever response arrives last
    2. BRemove all dependencies from the Effect
    3. CIgnore stale results or cancel obsolete work
    Show answer

    Answer: C (Ignore stale results or cancel obsolete work)

    Tie results to the active request. Cancellation can reduce work; stale-result guards preserve UI correctness.

  30. 30.

    A tooltip must measure layout before the browser paints a corrected position. Which Hook fits?

    mid
    1. AuseId
    2. BuseLayoutEffect
    3. CuseDebugValue
    Show answer

    Answer: B (useLayoutEffect)

    Layout Effects run before repaint and can block it, so reserve them for layout-sensitive work.

  31. 31.

    Does useEffect execute while producing server-rendered HTML?

    easy
    1. ANo, it runs on the client
    2. BYes, before every server template
    3. COnly if the dependency array is empty
    Show answer

    Answer: A (No, it runs on the client)

    Effects require the client lifecycle. Server output must not depend on an Effect having already run.

  32. 32.

    When is useEffectEvent appropriate?

    hard
    1. ATo remove every dependency from every Effect
    2. BTo create a general callback passed to children
    3. CAn event inside Effect logic needs latest values without resubscribing for those values
    Show answer

    Answer: C (An event inside Effect logic needs latest values without resubscribing for those values)

    Effect Events separate non-reactive event logic inside Effects; they are not an escape hatch for missing dependencies.

  33. 33.

    Why is useState after a conditional early return unsafe?

    easy
    1. AEarly returns are invalid JavaScript
    2. BState always becomes global
    3. CHook order can differ between renders
    Show answer

    Answer: C (Hook order can differ between renders)

    Ordinary Hooks must execute in a consistent order for each component instance.

  34. 34.

    Two components call the same custom state Hook. What do they share automatically?

    easy
    1. AA single component key
    2. BThe reusable logic, not the individual state instances
    3. CAll Hook state
    Show answer

    Answer: B (The reusable logic, not the individual state instances)

    Custom Hooks reuse logic. Shared state requires an explicit shared owner or store.

  35. 35.

    Which work should stay outside a reducer?

    mid
    1. ASending an HTTP request
    2. BCalculating a next-state value
    3. CChoosing a branch from an action type
    Show answer

    Answer: A (Sending an HTTP request)

    Reducers should be pure and return next state. Side effects belong at an appropriate interaction or synchronization boundary.

  36. 36.

    What should an action such as {type: 'itemRemoved', id} primarily communicate?

    mid
    1. AEvery DOM operation required
    2. BA request to mutate all objects
    3. CA meaningful event or state transition
    Show answer

    Answer: C (A meaningful event or state transition)

    Domain-oriented actions make reducer transitions understandable and testable without coupling them to DOM details.

  37. 37.

    Changing ref.current does what by itself?

    easy
    1. AResets all state
    2. BDoes not request a render
    3. CAlways requests two renders
    Show answer

    Answer: B (Does not request a render)

    Refs retain mutable values outside rendering's reactive state mechanism. Use state for values the UI must react to.

  38. 38.

    What is useDebugValue designed for?

    mid
    1. ALabeling custom Hook information in React DevTools
    2. BDisplaying text in the page
    3. CScheduling background tasks
    Show answer

    Answer: A (Labeling custom Hook information in React DevTools)

    It provides diagnostic labels for custom Hooks rather than application state or visible UI.

  39. 39.

    Should useId generate keys for records in a list?

    mid
    1. AYes, it tracks database identity automatically
    2. BOnly when records can reorder
    3. CNo, keys should come from stable data identity
    Show answer

    Answer: C (No, keys should come from stable data identity)

    useId associates generated IDs with component calls, not with the identity of data records.

  40. 40.

    How does the use API differ from ordinary Hooks regarding conditional calls?

    hard
    1. AIt must run only in event handlers
    2. BIt can read a resource inside conditions, while still requiring a component or Hook context
    3. CEvery Hook can now run conditionally
    Show answer

    Answer: B (It can read a resource inside conditions, while still requiring a component or Hook context)

    The use API has a documented conditional-call exception; this does not change the rules for useState or useEffect.

  41. 41.

    Two providers for the same context surround a consumer. Which value does it read?

    easy
    1. AA merge of both values
    2. BThe nearest matching provider above it
    3. CThe first provider created in the app
    Show answer

    Answer: B (The nearest matching provider above it)

    Context lookup follows the component ancestry to the closest provider of that context.

  42. 42.

    A provider explicitly supplies undefined. Does the consumer receive the context default?

    easy
    1. ANo, it receives undefined
    2. BYes, defaults replace all falsy values
    3. COnly if it uses memo
    Show answer

    Answer: A (No, it receives undefined)

    The default applies when no matching provider exists, not when a provider supplies undefined.

  43. 43.

    Can memo alone block an update from a context that the component consumes?

    mid
    1. AYes, if props are empty
    2. BYes, if the provider is a parent
    3. CNo
    Show answer

    Answer: C (No)

    Context changes reach consumers independently of the memo comparison of props.

  44. 44.

    Why can {user, logout} created inline as a provider value cause extra consumer renders?

    mid
    1. AFunctions are forbidden in context
    2. BIts object identity changes on parent renders
    3. CContext compares source-code strings
    Show answer

    Answer: B (Its object identity changes on parent renders)

    A new reference is a changed context value even when its contents are equivalent.

  45. 45.

    A rapidly changing cursor position shares context with a static theme. What can reduce unrelated updates?

    mid
    1. ASeparate contexts by update pattern
    2. BAdd more fields to the same value
    3. CUse random provider keys
    Show answer

    Answer: A (Separate contexts by update pattern)

    Splitting frequently changing state from stable values narrows which consumers receive each update.

  46. 46.

    What should getSnapshot return while an external store has not changed?

    hard
    1. AA fresh equivalent object on every call
    2. BA Promise on every call
    3. CA cached, stable snapshot value
    Show answer

    Answer: C (A cached, stable snapshot value)

    useSyncExternalStore depends on snapshot consistency; unstable snapshots can cause repeated rendering.

  47. 47.

    What must an external store subscription function normally return?

    mid
    1. AThe store's entire history
    2. BA function that unsubscribes
    3. CThe next component's JSX
    Show answer

    Answer: B (A function that unsubscribes)

    React needs to detach the listener when the subscription changes or the consumer unmounts.

  48. 48.

    Why provide getServerSnapshot for a server-rendered external-store consumer?

    hard
    1. ATo supply consistent server and initial hydration data
    2. BTo send browser event handlers to the database
    3. CTo eliminate authentication checks
    Show answer

    Answer: A (To supply consistent server and initial hydration data)

    A matching initial snapshot avoids rendering different store values across the server-client boundary.

  49. 49.

    What does useCallback cache?

    easy
    1. AA function reference
    2. BThe function's returned value
    3. CA network response
    Show answer

    Answer: A (A function reference)

    useCallback preserves a function identity while its dependencies match; it does not run and cache the function result.

  50. 50.

    Why must a useMemo calculation be pure?

    mid
    1. AIt executes only on a server
    2. BIt is a cleanup callback
    3. CReact may evaluate it again or discard cached work
    Show answer

    Answer: C (React may evaluate it again or discard cached work)

    Memoization is an optimization, not a guarantee of exactly-once execution or permanent storage.

  51. 51.

    A memoized child receives a new object prop on every render. What commonly happens?

    mid
    1. AThe child is permanently skipped
    2. BIts props comparison sees a changed reference
    3. CReact deep-compares every property automatically
    Show answer

    Answer: B (Its props comparison sees a changed reference)

    Default memo comparison checks each prop with Object.is rather than recursively comparing object contents.

  52. 52.

    A custom memo comparator ignores a changed callback prop. What can go wrong?

    hard
    1. AThe child keeps a callback capturing old state
    2. BThe callback becomes a server action
    3. CAll closures automatically refresh
    Show answer

    Answer: A (The child keeps a callback capturing old state)

    Declaring unequal props equal can preserve stale behavior, not just stale appearance.

  53. 53.

    What should justify introducing memoization around a component?

    mid
    1. AThe number of lines in its file
    2. BHaving any prop at all
    3. CMeasured expensive repeated rendering
    Show answer

    Answer: C (Measured expensive repeated rendering)

    Measure the relevant interaction before and after; comparison and caching also have costs.

  54. 54.

    Should useMemo be relied on to hold an essential mutable connection forever?

    mid
    1. AOnly if it has no dependencies
    2. BNo, use an appropriate lifecycle-managed resource
    3. CYes, its cache cannot be discarded
    Show answer

    Answer: B (No, use an appropriate lifecycle-managed resource)

    React may discard memo caches. Correctness should not depend on a performance cache's lifetime.

  55. 55.

    What is React Compiler intended to automate?

    mid
    1. AMemoization of compatible components and values
    2. BServer authorization
    3. CDatabase schema migration
    Show answer

    Answer: A (Memoization of compatible components and values)

    Compiler optimization relies on React's rules; it does not replace correctness, data security or application architecture.

  56. 56.

    What does a Profiler measurement help inspect?

    hard
    1. AEvery database query automatically
    2. BOnly source-file size
    3. CRendering cost associated with commits
    Show answer

    Answer: C (Rendering cost associated with commits)

    Use React profiling alongside browser tools; it does not fully explain network, layout or server bottlenecks.

  57. 57.

    Should the state directly controlling a text input be updated only as a Transition?

    mid
    1. AYes, to delay all keystrokes
    2. BOnly when typing quickly
    3. CNo, keep the input update urgent
    Show answer

    Answer: C (No, keep the input update urgent)

    Controlled text inputs need synchronous feedback. Defer the expensive results work instead of delaying the input value.

  58. 58.

    What can happen to non-urgent render work during an urgent update?

    hard
    1. AIt becomes a browser worker automatically
    2. BIt can be interrupted and restarted
    3. CIt must block every user interaction
    Show answer

    Answer: B (It can be interrupted and restarted)

    Concurrent scheduling can prioritize urgent work; rendering must remain pure because unfinished work may be abandoned.

  59. 59.

    Does useDeferredValue by itself debounce network requests?

    mid
    1. ANo
    2. BYes, always by 300 milliseconds
    3. COnly when the value is an object
    Show answer

    Answer: A (No)

    Deferring a rendered value changes UI scheduling, not a network rate policy. Debounce or cache requests separately when needed.

  60. 60.

    Which Hook provides an isPending flag for its transitions?

    mid
    1. AuseRef
    2. BuseImperativeHandle
    3. CuseTransition
    Show answer

    Answer: C (useTransition)

    useTransition exposes pending state along with its startTransition function; the standalone function does not expose a flag.

  61. 61.

    Does startTransition move a heavy synchronous JavaScript calculation off the main thread?

    hard
    1. AOnly in production
    2. BNo
    3. CYes, to a new worker
    Show answer

    Answer: B (No)

    Transition prioritizes React updates. CPU-heavy work still needs algorithmic improvements, chunking or a worker when appropriate.

  62. 62.

    A search result list uses a deferred query. How should its temporary old results be interpreted?

    mid
    1. AThey may intentionally lag behind the input
    2. BThey necessarily prove a cache bug
    3. CThey are guaranteed to match every keystroke
    Show answer

    Answer: A (They may intentionally lag behind the input)

    Deferred rendering can retain prior content while new work proceeds; indicate staleness when useful.

  63. 63.

    For versions with the documented async Transition caveat, how should setters after await be marked as transitions?

    hard
    1. AAssume all future timers inherit the scope
    2. BReplace them with direct DOM mutation
    3. CWrap those setters in another startTransition
    Show answer

    Answer: C (Wrap those setters in another startTransition)

    Transition context after await has a documented limitation; consult the installed React version rather than assuming propagation.

  64. 64.

    Why is writing analytics during render unsafe under concurrent rendering?

    hard
    1. ARender always commits exactly once
    2. BAn abandoned render can still have performed the write
    3. CReact automatically deduplicates all analytics
    Show answer

    Answer: B (An abandoned render can still have performed the write)

    External writes are not rolled back when React abandons render work. Put them at a suitable event or committed lifecycle boundary.

  65. 65.

    What does React.lazy normally expect its loader Promise to resolve to?

    mid
    1. AA CSS stylesheet string
    2. BA module object with a default component export
    3. CA raw DOM node
    Show answer

    Answer: B (A module object with a default component export)

    lazy uses the resolved default export as the component. Adapt a named export explicitly if needed.

  66. 66.

    Where should a lazy component declaration normally live?

    mid
    1. AOutside rendering, at module scope
    2. BInside every list iteration
    3. CInside the component's click handler
    Show answer

    Answer: A (Outside rendering, at module scope)

    A stable declaration avoids creating a different lazy component identity and resetting state repeatedly.

  67. 67.

    Will a plain fetch started in useEffect automatically activate Suspense?

    mid
    1. AYes, every Promise activates it
    2. BOnly if the URL ends in JSON
    3. CNo
    Show answer

    Answer: C (No)

    Suspense reacts to supported suspending resources or lazy components, not arbitrary asynchronous work in Effects.

  68. 68.

    What primarily determines a useful Suspense boundary location?

    mid
    1. AA requirement for one boundary per DOM element
    2. BWhich content should reveal or load together
    3. CThe alphabetic order of component names
    Show answer

    Answer: B (Which content should reveal or load together)

    Boundaries should reflect a coherent loading experience rather than implementation file boundaries.

  69. 69.

    A lazy import rejects. Which mechanism handles its render error?

    mid
    1. AAn appropriate Error Boundary
    2. BThe Suspense fallback alone
    3. CA CSS loading animation
    Show answer

    Answer: A (An appropriate Error Boundary)

    Suspense handles waiting; rejected loading work becomes an error handled by an error boundary.

  70. 70.

    Why avoid creating a fresh uncached Promise for a use read every client render?

    hard
    1. APromises cannot resolve to data
    2. Buse only accepts strings
    3. CIt can repeatedly suspend and restart work
    Show answer

    Answer: C (It can repeatedly suspend and restart work)

    Use a supported cache or resource source with stable Promise identity rather than manufacturing fresh work each render.

  71. 71.

    What do nested Suspense boundaries enable?

    mid
    1. AGuaranteed parallel database queries
    2. BIndependent progressive reveal of different UI regions
    3. CAutomatic server authorization
    Show answer

    Answer: B (Independent progressive reveal of different UI regions)

    Each boundary defines its own waiting UI. It does not alone determine how underlying data is requested.

  72. 72.

    A component suspends before its first successful mount. Should it rely on local state from that abandoned attempt being preserved?

    hard
    1. ANo
    2. BYes, every initializer is retained forever
    3. COnly if the fallback contains a form
    Show answer

    Answer: A (No)

    React retries the initial tree when ready; initialization must be safe to repeat.

  73. 73.

    Will an Error Boundary normally catch a throw inside a click handler?

    mid
    1. ANo, handle interaction errors explicitly
    2. BYes, all JavaScript errors are caught
    3. COnly if the button has a key
    Show answer

    Answer: A (No, handle interaction errors explicitly)

    Error Boundaries cover descendant rendering-related failures, not ordinary event-handler execution.

  74. 74.

    Can an Error Boundary catch an error in its own fallback render?

    mid
    1. AYes, by retrying itself forever
    2. BOnly in development
    3. CNo, an ancestor boundary is needed
    Show answer

    Answer: C (No, an ancestor boundary is needed)

    A boundary handles errors below it. Keep fallback rendering simple and place higher-level protection where useful.

  75. 75.

    A fetch rejects in an event handler. What is an appropriate response?

    easy
    1. AIgnore it because the component mounted
    2. BCatch it and set a visible error state
    3. CAssume Suspense handles it automatically
    Show answer

    Answer: B (Catch it and set a visible error state)

    Async event work needs explicit error handling or an action mechanism that provides an error path.

  76. 76.

    After a failed item detail page, why might a boundary be keyed by item ID?

    mid
    1. ATo reset error state when a different item is selected
    2. BTo authorize the item
    3. CTo stop all future network requests
    Show answer

    Answer: A (To reset error state when a different item is selected)

    Reset identity should reflect a meaningful new recovery attempt rather than change randomly every render.

  77. 77.

    What belongs in client error reporting?

    mid
    1. APasswords and session cookies
    2. BOnly a generic success message
    3. CUseful context with sensitive values removed
    Show answer

    Answer: C (Useful context with sensitive values removed)

    Collect actionable diagnostics while avoiding accidental disclosure of user data or credentials.

  78. 78.

    Why put a boundary around an optional recommendation widget?

    mid
    1. AIt replaces all tests
    2. BIts failure need not remove the entire page
    3. CIt guarantees the widget cannot fail
    Show answer

    Answer: B (Its failure need not remove the entire page)

    A local recovery boundary can isolate a nonessential feature while preserving the primary workflow.

  79. 79.

    Why is blindly rerendering a failed component in a tight loop a poor recovery strategy?

    hard
    1. AThe unchanged cause can trigger repeated failures
    2. BEvery error resolves after one rerender
    3. CReact forbids retry buttons
    Show answer

    Answer: A (The unchanged cause can trigger repeated failures)

    Recovery should change conditions or allow a bounded user-driven retry rather than hammer the same failure.

  80. 80.

    Should an invalid email field normally crash into an Error Boundary?

    easy
    1. AYes, all invalid input is an exception
    2. BOnly when the input is controlled
    3. CNo, show expected validation feedback
    Show answer

    Answer: C (No, show expected validation feedback)

    Expected user mistakes are ordinary form state; boundaries handle unexpected rendering failures.

  81. 81.

    When is a DOM ref normally available for imperative work?

    easy
    1. ABefore its first render starts
    2. BAs soon as the module imports
    3. CAfter React commits the element
    Show answer

    Answer: C (After React commits the element)

    The DOM node is assigned during commit. Event handlers and suitable Effects can access it afterward.

  82. 82.

    Why expose a small handle such as focus through useImperativeHandle?

    mid
    1. ATo turn a DOM node into context
    2. BTo limit the imperative API a parent depends on
    3. CTo force every prop update
    Show answer

    Answer: B (To limit the imperative API a parent depends on)

    A narrow handle can hide implementation details and reduce coupling to the child's DOM structure.

  83. 83.

    In React 19 function components, how can a component receive a ref?

    mid
    1. AThrough a ref prop
    2. BOnly through a class constructor
    3. COnly through a global registry
    Show answer

    Answer: A (Through a ref prop)

    React 19 supports ref as a prop for function components; older code commonly uses forwardRef.

  84. 84.

    A button is rendered through a portal. How do its React events propagate?

    mid
    1. AOnly through the portal container's React siblings
    2. BThey never propagate
    3. CThrough the React component tree
    Show answer

    Answer: C (Through the React component tree)

    Portals change DOM placement without changing React ancestry, including context and React event propagation.

  85. 85.

    Can portal content consume context from its React ancestors?

    mid
    1. AOnly if it is rendered twice
    2. BYes
    3. CNo, DOM placement breaks context
    Show answer

    Answer: B (Yes)

    A portal remains part of the original React tree despite being mounted into another DOM container.

  86. 86.

    Does creating a portal automatically provide modal focus management?

    mid
    1. ANo
    2. BYes, including focus restoration
    3. COnly if the container is body
    Show answer

    Answer: A (No)

    A modal still needs appropriate focus behavior, labeling and keyboard handling; DOM placement alone is insufficient.

  87. 87.

    Why can a newly created ref callback cause repeated detach and attach work?

    mid
    1. ACallbacks cannot reference DOM nodes
    2. BThe browser clones the element
    3. CReact receives a different callback identity
    Show answer

    Answer: C (React receives a different callback identity)

    Stable callback identity can avoid unnecessary ref teardown and setup when the referenced node has not changed.

  88. 88.

    Why is manually deleting a React-managed child node risky?

    hard
    1. AReact automatically imports the deletion into state
    2. BReact's next commit can conflict with the mutated DOM
    3. CIt always improves reconciliation
    Show answer

    Answer: B (React's next commit can conflict with the mutated DOM)

    Prefer declarative changes; imperative integrations need a clear boundary around DOM that React does not manage internally.

  89. 89.

    What does useActionState primarily connect to component state?

    mid
    1. AThe nearest DOM ref
    2. BThe result of an action
    3. CThe global browser history
    Show answer

    Answer: B (The result of an action)

    It maintains state based on action results and exposes an action dispatcher and pending information.

  90. 90.

    What is the first argument supplied to an action wrapped by useActionState?

    mid
    1. AThe previous action state
    2. BAlways the submit event
    3. CThe component's key
    Show answer

    Answer: A (The previous action state)

    The wrapped action receives the previous state before its payload, such as submitted FormData.

  91. 91.

    Where must a useFormStatus consumer be to observe a form's status?

    mid
    1. AOnly in the component that returns the form above it
    2. BAnywhere in the same module
    3. CInside a descendant of that form
    Show answer

    Answer: C (Inside a descendant of that form)

    The Hook reads the parent form's status, not a form rendered below the consumer in the same component.

  92. 92.

    What does a function passed to a form action receive for the submission?

    easy
    1. AThe entire React tree
    2. BFormData
    3. CA CSS selector
    Show answer

    Answer: B (FormData)

    Named form controls contribute submission values; server-side validation is still required.

  93. 93.

    Why does a submitted input generally need a name attribute?

    easy
    1. AIt supplies the field's FormData key
    2. BIt is required for every CSS rule
    3. CIt guarantees valid data
    Show answer

    Answer: A (It supplies the field's FormData key)

    A visible value alone does not define a submission key. Name and accessibility labeling serve different purposes.

  94. 94.

    What does useOptimistic support?

    mid
    1. AGuaranteed mutation success
    2. BPermanent browser caching
    3. CTemporary optimistic UI while an action is pending
    Show answer

    Answer: C (Temporary optimistic UI while an action is pending)

    Optimistic presentation must still reconcile with the confirmed result or error path.

  95. 95.

    Does using a Server Function for a form remove the need for authorization?

    mid
    1. AOnly for hidden inputs
    2. BNo
    3. CYes, because it is called from React
    Show answer

    Answer: B (No)

    Treat server entry points as untrusted request boundaries. Check identity, permissions and input on the server.

  96. 96.

    Inside a form, why give a non-submit button type button?

    easy
    1. AIts default behavior may otherwise submit the form
    2. BIt enables React rendering
    3. CIt disables keyboard interaction
    Show answer

    Answer: A (Its default behavior may otherwise submit the form)

    Explicit button types prevent accidental submission for actions such as opening a help panel.

  97. 97.

    What must a query cache key include for filtered search results?

    mid
    1. AParameters that change the requested result
    2. BOnly the component's display name
    3. COnly the current timestamp
    Show answer

    Answer: A (Parameters that change the requested result)

    Missing filters or tenant identity can make distinct requests incorrectly share cached data.

  98. 98.

    Does fetch normally reject its Promise just because the server returned 404?

    easy
    1. AYes, all non-200 responses reject
    2. BOnly in React components
    3. CNo, inspect the response status
    Show answer

    Answer: C (No, inspect the response status)

    fetch generally rejects for network-level failures; HTTP error statuses require explicit handling.

  99. 99.

    What does passing an AbortSignal to fetch enable?

    mid
    1. AGuaranteeing no packets were sent
    2. BCanceling obsolete client request work
    3. CUndoing a server mutation that already committed
    Show answer

    Answer: B (Canceling obsolete client request work)

    Aborting a request does not roll back server-side effects; mutation correctness still requires server design.

  100. 100.

    After successfully updating an item, which cached data may need attention?

    mid
    1. AIts detail and relevant list queries
    2. BOnly unrelated user preferences
    3. CNo data because React detects database writes
    Show answer

    Answer: A (Its detail and relevant list queries)

    Update or invalidate affected cached representations according to the cache library's policy.

  101. 101.

    What does a cache freshness window describe?

    mid
    1. AHow long the server guarantees truth
    2. BHow long React keeps a DOM node
    3. CHow long cached data is treated as fresh by the cache policy
    Show answer

    Answer: C (How long cached data is treated as fresh by the cache policy)

    Freshness is a client policy; the underlying data may change before that interval expires.

  102. 102.

    A second request requires an ID returned by the first. What is appropriate?

    mid
    1. AUse a random ID to parallelize them
    2. BStart it once the required ID exists
    3. CPretend both requests are independent
    Show answer

    Answer: B (Start it once the required ID exists)

    Parallelize independent work, but preserve genuine data dependencies and handle the first request's failure.

  103. 103.

    Why deduplicate identical in-flight reads?

    mid
    1. ATo avoid duplicate network work for the same resource
    2. BTo bypass response validation
    3. CTo make every response permanent
    Show answer

    Answer: A (To avoid duplicate network work for the same resource)

    A shared cache can let consumers reuse one request while retaining appropriate loading and error handling.

  104. 104.

    Why distinguish an empty result from a loading state?

    easy
    1. ABoth states always require a spinner
    2. BEmpty arrays cannot be rendered
    3. CAn empty successful response is meaningful completed data
    Show answer

    Answer: C (An empty successful response is meaningful completed data)

    Conflating them can leave a valid no-results response looking like an endless request.

  105. 105.

    Which state is often worth putting in the URL?

    easy
    1. AA user's password
    2. BAn uncommitted private access token
    3. CShareable search filters and page selection
    Show answer

    Answer: C (Shareable search filters and page selection)

    URL state enables links, refreshes and browser history, but is unsuitable for secrets.

  106. 106.

    For ordinary navigation, why prefer a link element over a clickable div?

    easy
    1. AIt guarantees server permission
    2. BIt supplies browser navigation and keyboard semantics
    3. CIt disables browser history
    Show answer

    Answer: B (It supplies browser navigation and keyboard semantics)

    Semantic links support expected interactions such as opening in a new tab.

  107. 107.

    How should an item ID read from a route be treated?

    mid
    1. AAs untrusted input requiring validation and authorization
    2. BAs already authorized by the router
    3. CAs always a number
    Show answer

    Answer: A (As untrusted input requiring validation and authorization)

    Routing identifies a requested resource; it does not prove the caller may access it.

  108. 108.

    Can a client-side protected-route component secure an API by itself?

    mid
    1. AYes, if it redirects quickly
    2. BOnly if its component is memoized
    3. CNo
    Show answer

    Answer: C (No)

    Client guards improve navigation experience; the API must enforce access independently.

  109. 109.

    What is a common benefit of nested route layouts?

    mid
    1. ARoutes no longer need URLs
    2. BShared UI can remain while child content changes
    3. CEvery navigation must reload all assets
    Show answer

    Answer: B (Shared UI can remain while child content changes)

    Layout nesting can preserve shared structure and local state, subject to the router's identity rules.

  110. 110.

    Changing sort order while on page 12 may require what?

    mid
    1. AResetting or validating the current page
    2. BDeleting browser history
    3. CKeeping page 12 unconditionally
    Show answer

    Answer: A (Resetting or validating the current page)

    The old page may be invalid for the new ordering or filter. Define a consistent URL-state transition.

  111. 111.

    How should an unmatched route normally be handled?

    easy
    1. AShow an indefinite loading spinner
    2. BTreat it as a successful empty dashboard
    3. CRender a deliberate not-found experience
    Show answer

    Answer: C (Render a deliberate not-found experience)

    A not-found route is a distinct outcome; server-rendered applications should also use an appropriate HTTP status.

  112. 112.

    What is a trade-off of prefetching route data?

    mid
    1. AIt always reduces transferred bytes
    2. BFaster navigation can consume bandwidth for unused routes
    3. CIt eliminates all loading states
    Show answer

    Answer: B (Faster navigation can consume bandwidth for unused routes)

    Choose prefetch triggers and cache policy based on likely navigation and resource cost.

  113. 113.

    Which API attaches React to HTML already rendered for the same tree?

    easy
    1. AcreateContext
    2. BhydrateRoot
    3. CcreatePortal
    Show answer

    Answer: B (hydrateRoot)

    Hydration reuses server-rendered markup and expects the initial client output to match it.

  114. 114.

    Why can rendering Date.now during both server and initial client rendering cause a warning?

    mid
    1. AThe generated text can differ
    2. BDates are invalid React children
    3. CHydration runs only at midnight
    Show answer

    Answer: A (The generated text can differ)

    Nondeterministic values should be serialized consistently or introduced after hydration where appropriate.

  115. 115.

    Why does reading window during server rendering fail?

    easy
    1. AReact never allows window access
    2. BJSX converts window to a prop
    3. CThe server environment has no browser window
    Show answer

    Answer: C (The server environment has no browser window)

    Use a browser-only lifecycle or framework boundary for browser APIs rather than assuming they exist during render.

  116. 116.

    What is suppressHydrationWarning intended for?

    mid
    1. ADisabling all client rendering
    2. BA narrow unavoidable mismatch escape hatch
    3. CFixing any inconsistent application tree
    Show answer

    Answer: B (A narrow unavoidable mismatch escape hatch)

    It should not hide broad server-client divergence or replace fixing deterministic initial output.

  117. 117.

    What can streaming server rendering improve?

    mid
    1. ADelivery of ready HTML while other regions wait
    2. BThe correctness of every API permission
    3. CThe browser's available memory
    Show answer

    Answer: A (Delivery of ready HTML while other regions wait)

    Streaming can reveal content progressively, but interactivity still depends on relevant client code and hydration.

  118. 118.

    Why is mutable module-level per-user state dangerous on a server?

    hard
    1. AEvery request necessarily gets a new process
    2. BModules are inaccessible to server code
    3. CIt can leak across requests handled by the process
    Show answer

    Answer: C (It can leak across requests handled by the process)

    Keep request-specific data scoped to the request and use caches with deliberate authorization-aware keys.

  119. 119.

    Does seeing server-rendered markup prove its click handlers are ready?

    mid
    1. AOnly for buttons
    2. BNo
    3. CYes, markup contains executable event handlers
    Show answer

    Answer: B (No)

    Visible HTML and hydrated interactivity are different stages; design loading behavior accordingly.

  120. 120.

    How can invalid HTML nesting contribute to hydration failures?

    mid
    1. AThe browser may repair the markup into a different tree
    2. BIt prevents all JavaScript downloads
    3. CReact always preserves invalid nesting literally
    Show answer

    Answer: A (The browser may repair the markup into a different tree)

    Write valid HTML so the parsed DOM structure agrees with the component tree expected during hydration.

  121. 121.

    What does a use client directive primarily establish in an RSC-compatible system?

    mid
    1. AA client module boundary
    2. BA guarantee the module never participates in server prerendering
    3. CA browser authentication policy
    Show answer

    Answer: A (A client module boundary)

    The directive marks client-side module dependencies; Client Components can still contribute initial server-rendered HTML.

  122. 122.

    Where should a database credential used by a Server Component remain?

    mid
    1. AIn props passed to a Client Component
    2. BIn a hidden DOM field
    3. CIn server-only code and environment
    Show answer

    Answer: C (In server-only code and environment)

    Server execution does not make serialized output secret. Never pass credentials into client-visible props or markup.

  123. 123.

    Which capability belongs in a Client Component rather than a Server Component?

    mid
    1. AProducing noninteractive markup
    2. BInteractive useState-driven input
    3. CReading server-accessible data
    Show answer

    Answer: B (Interactive useState-driven input)

    Stateful browser interaction requires a client boundary; Server Components can compose the surrounding UI.

  124. 124.

    Does use server mark a component as a Server Component?

    mid
    1. ANo, it marks Server Functions
    2. BYes, in every React application
    3. COnly for components named Server
    Show answer

    Answer: A (No, it marks Server Functions)

    Server Component selection is governed by the framework's module model, not a use server component marker.

  125. 125.

    What constraint applies to values crossing an RSC server-to-client boundary?

    mid
    1. AAny live database connection can cross
    2. BEvery value must be a plain string
    3. CThey must use the supported serialization format
    Show answer

    Answer: C (They must use the supported serialization format)

    The RSC format supports defined serializable values; arbitrary closures or resource handles are not transferable props.

  126. 126.

    Why is moving a secret-bearing module under use client dangerous?

    hard
    1. AIt only changes CSS ordering
    2. BIt may enter the client dependency graph
    3. CIt automatically encrypts the secret
    Show answer

    Answer: B (It may enter the client dependency graph)

    Keep server-only dependencies outside client imports and use framework checks to catch accidental boundary violations.

  127. 127.

    How should a Server Function treat an ID supplied by the client?

    mid
    1. AValidate it and authorize the operation
    2. BTrust it because React encoded it
    3. CUse it as proof of ownership
    Show answer

    Answer: A (Validate it and authorize the operation)

    The transport does not make arguments trustworthy. Every server mutation requires its own permission checks.

  128. 128.

    Are Server Components and server rendering to HTML the same mechanism?

    hard
    1. AYes, they are interchangeable names
    2. BOnly when no CSS is used
    3. CNo, they address different parts of rendering and delivery
    Show answer

    Answer: C (No, they address different parts of rendering and delivery)

    RSC determines where components execute and what is sent across the boundary; HTML SSR is a separate output step.

  129. 129.

    Why query a rendered button by role and accessible name?

    easy
    1. AIt checks the private Hook array
    2. BIt avoids rendering the component
    3. CIt approximates how users identify the control
    Show answer

    Answer: C (It approximates how users identify the control)

    Semantic queries encourage accessible markup and reduce coupling to internal implementation details.

  130. 130.

    A message appears after an async request. What should the test do?

    mid
    1. ASleep for a fixed minute
    2. BAwait an appropriate appearance query
    3. CAssert immediately and ignore failures
    Show answer

    Answer: B (Await an appropriate appearance query)

    Wait for observable UI behavior so the test is tied to completion rather than an arbitrary delay.

  131. 131.

    What does act help ensure in React tests?

    mid
    1. ARelevant updates are processed before assertions
    2. BNetwork calls never occur
    3. CEvery assertion is automatically correct
    Show answer

    Answer: A (Relevant updates are processed before assertions)

    act coordinates React updates; testing utilities often wrap interactions in it, but async work still needs proper awaiting.

  132. 132.

    Why simulate a realistic click rather than invoke a component's private handler directly?

    easy
    1. AIt skips event propagation
    2. BIt guarantees visual layout
    3. CIt exercises the rendered interaction boundary
    Show answer

    Answer: C (It exercises the rendered interaction boundary)

    A user-level interaction can catch wiring and disabled-state issues that a direct handler call misses.

  133. 133.

    What is a limitation of a large snapshot test?

    mid
    1. AIt replaces error-state tests
    2. BIt may pass while behavior or accessibility is wrong
    3. CIt proves every interaction works
    Show answer

    Answer: B (It may pass while behavior or accessibility is wrong)

    Snapshots compare output, not full user workflows. Review changes and add focused behavior assertions.

  134. 134.

    A component uses routing hooks. What must its test normally supply?

    mid
    1. AAn appropriate router environment
    2. BA random context provider
    3. CA real production login
    Show answer

    Answer: A (An appropriate router environment)

    Use a controlled router setup to test navigation state and links without unrelated production dependencies.

  135. 135.

    What should tests with fake timers do during cleanup?

    mid
    1. ALeave the fake clock active for later tests
    2. BDelete all state modules
    3. CRestore timers and handle pending work deliberately
    Show answer

    Answer: C (Restore timers and handle pending work deliberately)

    Leaking fake timers or scheduled work can make otherwise independent tests order-dependent.

  136. 136.

    Where is a useful place to mock data fetching for an integrated component test?

    mid
    1. ABy removing all loading UI
    2. BAt the network boundary
    3. CInside every internal state setter
    Show answer

    Answer: B (At the network boundary)

    Boundary mocks let the component's real state transitions run while responses remain controlled.

  137. 137.

    What type design can require href for a link variant but not a button variant?

    mid
    1. AAn untyped any prop
    2. BA discriminated union of props
    3. COne object with every field optional
    Show answer

    Answer: B (A discriminated union of props)

    A discriminant lets TypeScript enforce valid combinations and narrow each variant's required fields.

  138. 138.

    Why can currentTarget be easier to type for an input handler than target?

    mid
    1. AIt corresponds to the element handling the event
    2. BIt always contains a string
    3. CIt is never nullable in any API
    Show answer

    Answer: A (It corresponds to the element handling the event)

    React event types can describe the handler's element while the originating target may be more general.

  139. 139.

    A state value starts null and later holds a User. What annotation expresses this?

    easy
    1. AOnly null
    2. BAny by default
    3. CA union of User and null
    Show answer

    Answer: C (A union of User and null)

    An explicit union represents both loading or empty state and a valid user while preserving type checking.

  140. 140.

    Why must a DOM ref type generally allow null?

    easy
    1. AAll refs store JSON
    2. BThe element is absent before mount and after removal
    3. CReact never assigns DOM nodes
    Show answer

    Answer: B (The element is absent before mount and after removal)

    Check availability before imperative access, rather than asserting the node exists throughout the lifecycle.

  141. 141.

    Which React type commonly represents content accepted as children?

    mid
    1. AReactNode
    2. BCSSProperties
    3. CDispatch
    Show answer

    Answer: A (ReactNode)

    ReactNode covers renderable values; narrower types can be appropriate when the component intentionally restricts its content.

  142. 142.

    How can a wrapper button preserve native button prop types?

    mid
    1. AManually type every prop as string
    2. BUse only an index signature of any
    3. CDerive props from the native button component type
    Show answer

    Answer: C (Derive props from the native button component type)

    React's component prop utilities can preserve event, accessibility and native attribute types while adding custom fields.

  143. 143.

    Does asserting a JSON response as User validate it at runtime?

    mid
    1. AOnly in strict mode
    2. BNo
    3. CYes, TypeScript checks downloaded bytes
    Show answer

    Answer: B (No)

    Type assertions are erased. Validate unknown external data at runtime when correctness requires it.

  144. 144.

    What can an exhaustive action switch detect?

    hard
    1. AA newly added action missing reducer handling
    2. BEvery possible network error
    3. CAll stale closures
    Show answer

    Answer: A (A newly added action missing reducer handling)

    A discriminated action union and never check make missing cases visible to the type checker.

  145. 145.

    An icon-only button needs what for assistive technology?

    easy
    1. AAn accessible name
    2. BOnly a tooltip visible on hover
    3. CA random test ID
    Show answer

    Answer: A (An accessible name)

    Provide meaningful labeling through visible hidden text or an appropriate ARIA label; a decorative icon alone is insufficient.

  146. 146.

    What connects a label to a separate input in JSX?

    easy
    1. AThe label's className
    2. BIdentical placeholder text
    3. ChtmlFor matching the input ID
    Show answer

    Answer: C (htmlFor matching the input ID)

    Explicit labels associate the visible description with the control. IDs must be unique within the document.

  147. 147.

    How can a non-focus-changing async status be announced?

    mid
    1. ARenaming the component file
    2. BAn appropriately configured live region
    3. CChanging only text color
    Show answer

    Answer: B (An appropriately configured live region)

    Use live announcements thoughtfully so updates are discoverable without overwhelming assistive technology.

  148. 148.

    Do stable React keys provide visible or accessible labels automatically?

    mid
    1. ANo
    2. BYes, screen readers read every key
    3. COnly for numeric keys
    Show answer

    Answer: A (No)

    Keys are internal identity information and do not replace semantic names, labels or content.

  149. 150.

    How can a field expose its error message programmatically?

    mid
    1. ARemove its label
    2. BAssociate error text using an appropriate description and invalid state
    3. CUse only a red border
    Show answer

    Answer: B (Associate error text using an appropriate description and invalid state)

    Make the error available as text and connected to the control, not just a visual color change.

  150. 151.

    What preference should an animated React interface respect?

    easy
    1. Aprefers-reduced-motion
    2. BThe alphabetic order of classes
    3. CThe number of installed fonts
    Show answer

    Answer: A (prefers-reduced-motion)

    Offer reduced animation where motion can be distracting or uncomfortable, without hiding necessary feedback.

  151. 152.

    Why avoid positive tabIndex values as a general focus strategy?

    mid
    1. AThey make all elements semantic buttons
    2. BThey are required for every modal
    3. CThey create brittle custom tab ordering
    Show answer

    Answer: C (They create brittle custom tab ordering)

    Prefer natural DOM order and semantic controls; use deliberate focus management for specific composite widgets.

  152. 153.

    How does React normally render an untrusted string child containing markup?

    easy
    1. AAs executable HTML
    2. BAs a component import
    3. CAs escaped text
    Show answer

    Answer: C (As escaped text)

    Normal string rendering does not parse the string as HTML. Explicit raw-HTML insertion has different risks.

  153. 154.

    What is required before injecting untrusted rich HTML?

    mid
    1. AReplacing spaces
    2. BA suitable sanitization policy at a trusted boundary
    3. COnly memoizing the string
    Show answer

    Answer: B (A suitable sanitization policy at a trusted boundary)

    Raw HTML bypasses normal text escaping. Sanitization must address the allowed HTML and URL contexts.

  154. 155.

    Can a hidden form field be trusted as the product's true price?

    easy
    1. ANo, the server must determine or verify it
    2. BYes, users cannot see hidden fields
    3. COnly when React controls its value
    Show answer

    Answer: A (No, the server must determine or verify it)

    Client values can be changed outside the UI. Calculate authoritative prices and permissions on the server.

  155. 156.

    What should you assume about an environment value embedded in a browser bundle?

    mid
    1. AIt is encrypted by the build
    2. BIt is visible only to React
    3. CUsers can inspect it
    Show answer

    Answer: C (Users can inspect it)

    Build-time environment substitution does not create secrecy. Keep private credentials on the server.

  156. 157.

    Why does storing a token in localStorage not protect it from same-origin script compromise?

    mid
    1. AReact encrypts its keys
    2. BJavaScript on the origin can read it
    3. ClocalStorage is automatically HttpOnly
    Show answer

    Answer: B (JavaScript on the origin can read it)

    Token storage choices need a threat model; client storage is not a defense against executing malicious same-origin scripts.

  157. 158.

    What should a user-supplied navigation URL be checked against?

    mid
    1. AAllowed schemes and destinations as appropriate
    2. BOnly its string length
    3. COnly whether it contains a dot
    Show answer

    Answer: A (Allowed schemes and destinations as appropriate)

    URL handling has risks beyond text escaping, including unwanted schemes or redirects.

  158. 159.

    Cookie-authenticated mutations may need which server-side protection?

    mid
    1. AA React key
    2. BA client-only disabled button
    3. CAn appropriate CSRF defense
    Show answer

    Answer: C (An appropriate CSRF defense)

    Browsers can attach cookies automatically. Use suitable same-site policy and CSRF protections for the application's request model.

  159. 160.

    What helps manage frontend dependency risk?

    mid
    1. ACopying credentials into lockfiles
    2. BReviewing updates and maintaining a dependency inventory
    3. CAssuming popular packages cannot be compromised
    Show answer

    Answer: B (Reviewing updates and maintaining a dependency inventory)

    Dependencies execute code in builds or clients. Review changes, provenance and advisories with the project's security process.

  160. 161.

    Two sibling widgets must edit the same selection. Where should its shared source of truth normally be?

    easy
    1. AA random DOM attribute
    2. BTheir closest suitable common owner
    3. CIndependent duplicate state in both widgets
    Show answer

    Answer: B (Their closest suitable common owner)

    A shared owner coordinates updates; duplicated authoritative state can diverge.

  161. 162.

    What is a useful criterion for a feature module boundary?

    mid
    1. AA cohesive user capability and its contracts
    2. BAn arbitrary number of files
    3. COne module for every HTML tag
    Show answer

    Answer: A (A cohesive user capability and its contracts)

    Feature boundaries should reduce coupling and make ownership and dependencies understandable.

  162. 163.

    What should a shared design-system component prioritize?

    mid
    1. AEvery product-specific network request
    2. BHidden global business state
    3. CStable behavior, accessibility and documented variants
    Show answer

    Answer: C (Stable behavior, accessibility and documented variants)

    Shared UI benefits from predictable contracts rather than embedding unrelated domain workflows.

  163. 164.

    What does a headless component or Hook typically separate?

    mid
    1. ATypeScript from JavaScript
    2. BBehavior from visual rendering
    3. CClient code from every network request
    Show answer

    Answer: B (Behavior from visual rendering)

    Headless APIs let callers control appearance while reusing interaction and state logic.

  164. 165.

    What makes a reusable component externally controlled?

    mid
    1. AIts authoritative value and update request come through props
    2. BIt never rerenders
    3. CIt uses no event handlers
    Show answer

    Answer: A (Its authoritative value and update request come through props)

    The caller owns the value; the component reports requested changes instead of silently creating a competing source of truth.

  165. 166.

    What can React Activity preserve while its content is hidden?

    hard
    1. AAll Effects running unchanged forever
    2. BA guarantee that no work is ever scheduled
    3. CComponent state while Effects are cleaned up
    Show answer

    Answer: C (Component state while Effects are cleaned up)

    Activity provides a lifecycle-aware hidden boundary rather than simply removing the component and its state.

  166. 167.

    Why keep a domain rule such as order eligibility outside a presentational button?

    mid
    1. AReact automatically enforces domain rules
    2. BIt can be reused and verified at appropriate boundaries
    3. CButtons cannot receive booleans
    Show answer

    Answer: B (It can be reused and verified at appropriate boundaries)

    Presentation can show the decision, while authoritative business enforcement still belongs on the server.

  167. 168.

    What is a cost of splitting one UI into independently deployed microfrontends?

    hard
    1. ACoordination of shared contracts, routing and dependencies
    2. BAutomatic elimination of integration bugs
    3. CGuaranteed smaller total bundles
    Show answer

    Answer: A (Coordination of shared contracts, routing and dependencies)

    Independent delivery trades against runtime integration and consistency complexity; it is not free modularity.

  168. 169.

    What helps a bundler remove unused code?

    mid
    1. AAnalyzable module exports and accurate side-effect information
    2. BImporting the entire library into a global
    3. CRenaming every file index
    Show answer

    Answer: A (Analyzable module exports and accurate side-effect information)

    Tree shaking relies on module analysis and side-effect assumptions; incorrect package metadata can also remove needed behavior.

  169. 170.

    What commonly creates an asynchronous bundle boundary?

    mid
    1. AAn ordinary function call
    2. BA CSS class name
    3. CA supported dynamic import
    Show answer

    Answer: C (A supported dynamic import)

    Bundlers can split dynamic imports into separately loaded chunks; verify the actual output rather than assuming a split.

  170. 171.

    Why retain usable source maps for production error diagnosis under a deliberate access policy?

    mid
    1. AThey encrypt browser code
    2. BThey map transformed stack traces to original code
    3. CThey prevent runtime exceptions
    Show answer

    Answer: B (They map transformed stack traces to original code)

    Source maps aid debugging but may expose source details; decide how to publish or upload them appropriately.

  171. 172.

    Why use content-hashed asset filenames?

    mid
    1. AChanged content receives a different cacheable URL
    2. BThey authenticate users
    3. CThey remove the need for HTML
    Show answer

    Answer: A (Changed content receives a different cacheable URL)

    Hashed assets enable long-lived caching while HTML can reference newly built versions.

  172. 173.

    A small screen downloads a large JavaScript bundle. What is a useful first investigation?

    mid
    1. AAdd memo to every component
    2. BIncrease the page's font size
    3. CInspect a bundle report and import graph
    Show answer

    Answer: C (Inspect a bundle report and import graph)

    Bundle analysis identifies expensive dependencies and accidental eager imports, which rendering memoization does not fix.

  173. 174.

    If configuration is compiled into static JavaScript, does changing a server environment variable necessarily update it?

    mid
    1. AOnly on Tuesdays
    2. BNo, a rebuild or explicit runtime configuration path may be needed
    3. CYes, browsers reread server variables automatically
    Show answer

    Answer: B (No, a rebuild or explicit runtime configuration path may be needed)

    Build-time values are embedded in artifacts. Runtime configuration must be implemented separately if required.

  174. 175.

    Why compare performance using a suitable production or profiling build?

    mid
    1. ADevelopment checks and tooling alter costs
    2. BProduction never has bugs
    3. CDevelopment rendering uses no JavaScript
    Show answer

    Answer: A (Development checks and tooling alter costs)

    Measure a representative build and device; development behavior can distort performance conclusions.

  175. 176.

    What should be tested when lazy components load their own styles?

    hard
    1. AOnly the component filename
    2. BWhether CSS has React keys
    3. CLoading order and unstyled or shifted content
    Show answer

    Answer: C (Loading order and unstyled or shifted content)

    Code splitting can change when styles arrive. Verify first render, navigation and loading transitions.

  176. 177.

    What do CSS Modules primarily provide?

    easy
    1. AAutomatic translation of text
    2. BServer-side form validation
    3. CLocally scoped class-name mappings
    Show answer

    Answer: C (Locally scoped class-name mappings)

    CSS Modules reduce class naming collisions through build-time mappings; they do not isolate every possible global style effect.

  177. 178.

    For many length-valued inline style properties, what does React do with numeric values?

    easy
    1. ARejects all numbers
    2. BAdds pixel units where appropriate
    3. CTreats every number as a percentage
    Show answer

    Answer: B (Adds pixel units where appropriate)

    Some properties are unitless. Use explicit strings when a particular non-pixel unit is required.

  178. 179.

    What can combine semantic theme state with efficient styling?

    mid
    1. AA theme setting that selects CSS variables
    2. BDuplicating every component for each color
    3. CUpdating thousands of independent color states
    Show answer

    Answer: A (A theme setting that selects CSS variables)

    CSS variables can propagate visual tokens while React manages meaningful theme selection.

  179. 180.

    Which styling approach helps adapt layouts to right-to-left languages?

    mid
    1. AHardcoding left for every leading edge
    2. BReversing every string
    3. CLogical properties such as margin-inline-start
    Show answer

    Answer: C (Logical properties such as margin-inline-start)

    Logical directions follow writing mode; language support also requires correct content and interaction behavior.

  180. 181.

    Why avoid building plural messages by simply appending s?

    mid
    1. AEvery language has exactly two plural forms
    2. BPlural rules vary across languages
    3. CReact cannot render suffixes
    Show answer

    Answer: B (Plural rules vary across languages)

    Use a translation system with plural selection rather than English-specific string construction.

  181. 182.

    What should determine user-visible date formatting?

    mid
    1. AAn explicit locale and time-zone policy
    2. BThe developer's laptop settings only
    3. CThe order of components
    Show answer

    Answer: A (An explicit locale and time-zone policy)

    Consistent formatting matters for both usability and hydration; server and client need compatible initial assumptions.

  182. 183.

    Why are complete translated messages preferable to concatenated fragments?

    mid
    1. ATranslation files cannot contain variables
    2. BReact sorts words alphabetically
    3. CWord order and grammar differ across languages
    Show answer

    Answer: C (Word order and grammar differ across languages)

    Use placeholders within complete messages so translators can reorder language naturally.

  183. 184.

    What helps avoid content jumping when images load?

    mid
    1. ADelay all text until the image loads
    2. BReserve space using dimensions or aspect ratio
    3. CSet every image key randomly
    Show answer

    Answer: B (Reserve space using dimensions or aspect ratio)

    Known geometry prevents surrounding content from moving as media dimensions become available.

  184. 185.

    How does class setState with an object differ from a Hook state setter?

    mid
    1. AHook setters shallow-merge but class setters replace
    2. BClass setState shallow-merges the partial state
    3. CBoth always deep-merge
    Show answer

    Answer: B (Class setState shallow-merges the partial state)

    Class state updates merge at the top level; useState replaces the state value supplied to it.

  185. 186.

    What often replaces componentWillUnmount cleanup when migrating subscriptions to Hooks?

    mid
    1. AThe cleanup returned by an Effect
    2. BA useMemo return value
    3. CA module export
    Show answer

    Answer: A (The cleanup returned by an Effect)

    Group resource setup and cleanup in the same synchronization boundary instead of translating lifecycle names mechanically.

  186. 187.

    What is a suitable direction when migrating legacy string refs?

    mid
    1. AMove ref names into CSS selectors
    2. BKeep them as authentication IDs
    3. CUse supported object or callback refs
    Show answer

    Answer: C (Use supported object or callback refs)

    Modern ref APIs make ownership and lifecycle clearer and avoid legacy string-ref limitations.

  187. 188.

    In React 19, what should replace reliance on removed findDOMNode behavior?

    mid
    1. AA global query for every div
    2. BAn explicit ref to the relevant DOM element
    3. CA new call to ReactDOM.render
    Show answer

    Answer: B (An explicit ref to the relevant DOM element)

    Explicit refs make the intended node part of the component's contract rather than searching through component internals.

  188. 189.

    What replaces ReactDOM.render in a modern client-only root?

    easy
    1. AcreateRoot followed by root.render
    2. BhydrateRoot for every empty container
    3. CcreatePortal without a root
    Show answer

    Answer: A (createRoot followed by root.render)

    Use createRoot for a new client root; hydrateRoot is for matching server-rendered markup.

  189. 190.

    What comparison does PureComponent use for class props and state?

    mid
    1. ARecursive database equality
    2. BA comparison of rendered pixels
    3. CShallow comparison
    Show answer

    Answer: C (Shallow comparison)

    Immutable updates matter because shallow comparisons cannot detect nested mutation behind the same reference.

  190. 191.

    What should a higher-order component generally preserve?

    mid
    1. AOnly its filename
    2. BThe wrapped component's intended prop contract
    3. CEvery global mutable variable
    Show answer

    Answer: B (The wrapped component's intended prop contract)

    Wrappers should forward appropriate props and document additions or collisions rather than silently changing behavior.

  191. 192.

    What is a render prop?

    mid
    1. AA function prop used to supply rendered content
    2. BA browser method that edits a DOM node
    3. CA rule that props must be strings
    Show answer

    Answer: A (A function prop used to supply rendered content)

    Render props share behavior while letting consumers determine UI; Hooks offer another reuse option with different ergonomics.

  192. 193.

    An autocomplete returns old suggestions after rapid typing. What invariant is missing?

    mid
    1. AResults must belong to the active query
    2. BEvery response must be displayed
    3. CSuggestions must be global state
    Show answer

    Answer: A (Results must belong to the active query)

    Track query or request identity so an older completion cannot overwrite newer results.

  193. 194.

    A chat reconnect replays previously received messages. How should the UI deduplicate?

    mid
    1. ABy displayed timestamp text alone
    2. BBy array position
    3. CBy a stable server message ID
    Show answer

    Answer: C (By a stable server message ID)

    Stable identity prevents duplicate display while allowing legitimate messages with identical text or time.

  194. 195.

    Why separate uploading from server processing in a file workflow?

    mid
    1. AReact cannot show multiple statuses
    2. BTransfer completion need not mean the file is ready
    3. CA progress bar proves validation passed
    Show answer

    Answer: B (Transfer completion need not mean the file is ready)

    The server may scan or transform a file after receipt; represent those states accurately.

  195. 196.

    When reordering editable cards, what should their keys follow?

    mid
    1. AThe cards' stable IDs
    2. BTheir current array indices
    3. CTheir current screen coordinates
    Show answer

    Answer: A (The cards' stable IDs)

    Stable identity keeps local state attached to the same logical card when positions change.

  196. 197.

    What information can support a reliable local undo operation?

    mid
    1. AOnly the button's color
    2. BA random timeout
    3. CA prior state or reversible domain operation
    Show answer

    Answer: C (A prior state or reversible domain operation)

    Undo requires enough history to restore intent; remote collaborative changes introduce additional reconciliation concerns.

  197. 198.

    What prevents a burst of notifications from overwhelming a screen reader?

    mid
    1. ARemoving all text labels
    2. BA deliberate announcement and queue policy
    3. CMaking every message assertive simultaneously
    Show answer

    Answer: B (A deliberate announcement and queue policy)

    Prioritize and batch appropriately so important feedback remains understandable rather than becoming competing announcements.

  198. 199.

    What constrains data sent to a Web Worker for heavy computation?

    hard
    1. ASupported structured-clone or transferable values
    2. BReact props syntax alone
    3. CAll functions can be copied directly
    Show answer

    Answer: A (Supported structured-clone or transferable values)

    Worker messaging has a serialization boundary. Design messages and transfer large buffers intentionally.

  199. 200.

    How can an editor detect that its saved record changed on the server?

    hard
    1. AAssume the last opened tab owns the record
    2. BCompare only the local component key
    3. CSend an expected version and handle a conflict response
    Show answer

    Answer: C (Send an expected version and handle a conflict response)

    Optimistic concurrency requires server participation and an explicit conflict-resolution experience.

  200. 201.

    You type something into each of the three uncontrolled inputs, then click "Remove first". What do you see?

    mid
    function Todos() {
      const [items, setItems] = useState(['a', 'b', 'c']);
      return (
        <>
          <button onClick={() => setItems(items.slice(1))}>Remove first</button>
          {items.map((item, i) => (
            <label key={i}>
              {item} <input />
            </label>
          ))}
        </>
      );
    }
    1. ARows b and c remain, each still showing the text you typed next to them
    2. BAll remaining inputs are cleared because the list re-rendered
    3. CLabels b and c remain, but their inputs show the text typed for a and b; the text typed for c is gone
    4. DReact warns about duplicate keys and keeps all three rows
    Show answer

    Answer: C (Labels b and c remain, but their inputs show the text typed for a and b; the text typed for c is gone)

    With key={i}, keys 0 and 1 still exist after the deletion, so React reuses those two DOM rows (including the uncontrolled input values) and removes the row with key 2. The label text updates from props, but the typed values stay where they were, so they appear attached to the wrong items. Use a stable id from the data as the key.

  201. 202.

    What does the button show after one click?

    easy
    function Counter() {
      const [count, setCount] = useState(0);
      function handleClick() {
        setCount(count + 1);
        setCount(count + 1);
        setCount(count + 1);
      }
      return <button onClick={handleClick}>{count}</button>;
    }
    1. A3
    2. B1
    3. C0
    4. DIt flashes 1, 2, 3 and settles on 3
    Show answer

    Answer: B (1)

    count is a snapshot: it is 0 for the whole event handler, so all three calls queue "set to 1". React batches them into a single re-render. To increment three times, use the updater form setCount(c => c + 1).

  202. 203.

    Starting from n = 0, what is n after one click?

    hard
    const [n, setN] = useState(0);
    
    function handleClick() {
      setN((x) => x + 1);
      setN(n + 5);
      setN((x) => x * 2);
    }
    1. A2
    2. B12
    3. C5
    4. D10
    Show answer

    Answer: D (10)

    React processes the queue in order: x => x + 1 gives 1, then setN(n + 5) replaces it with 0 + 5 (the snapshot value of n is 0), then x => x * 2 doubles 5 to 10. A plain value replaces whatever is queued before it; an updater function receives the result of the previous step.

  203. 204.

    name starts as 'Ada'. What does the click handler log?

    easy
    const [name, setName] = useState('Ada');
    
    function handleClick() {
      setName('Grace');
      console.log(name);
    }
    1. A'Ada'
    2. B'Grace'
    3. Cundefined
    4. DIt depends on whether React has already re-rendered
    Show answer

    Answer: A ('Ada')

    Setting state doesn't change the variable in the current render; it schedules a new render in which name will be 'Grace'. The running handler closed over the old snapshot, so it logs 'Ada' every time.

  204. 205.

    The component is rendered inside <StrictMode> in development. What is logged on mount?

    mid
    function ChatRoom() {
      useEffect(() => {
        console.log('connect');
        return () => console.log('disconnect');
      }, []);
      return <h1>Chat</h1>;
    }
    1. Aconnect
    2. Bconnect, connect
    3. Cconnect, disconnect, connect
    4. Ddisconnect, connect
    Show answer

    Answer: C (connect, disconnect, connect)

    In development, StrictMode runs one extra setup + cleanup cycle on mount to verify that your cleanup mirrors your setup. In production you only see connect. The fix for problems this exposes is a correct cleanup, not removing StrictMode.

  205. 206.

    In what order are the effects logged when Parent mounts?

    hard
    function Child() {
      useEffect(() => console.log('child effect'));
      useLayoutEffect(() => console.log('child layout'));
      return null;
    }
    
    function Parent() {
      useEffect(() => console.log('parent effect'));
      useLayoutEffect(() => console.log('parent layout'));
      return <Child />;
    }
    1. Aparent layout, child layout, parent effect, child effect
    2. Bchild layout, parent layout, child effect, parent effect
    3. Cchild layout, child effect, parent layout, parent effect
    4. Dparent effect, parent layout, child effect, child layout
    Show answer

    Answer: B (child layout, parent layout, child effect, parent effect)

    All layout effects run synchronously after the DOM is updated (before paint), then passive effects run later. Within each group, children run before parents, so a parent effect can rely on its children already being mounted.

  206. 207.

    A tooltip must measure its own height and reposition itself above its anchor without the user ever seeing it in the wrong spot. Where should you measure?

    mid
    1. AIn useEffect
    2. BDuring render, via ref.current.getBoundingClientRect()
    3. CIn useMemo with the anchor as a dependency
    4. DIn useLayoutEffect
    Show answer

    Answer: D (In useLayoutEffect)

    useLayoutEffect runs after the DOM is updated but before the browser paints, so you can measure and set state and the user only sees the final position. useEffect usually runs after paint, causing a visible flicker, and reading refs during render is unreliable because the DOM may not be updated yet.

  207. 208.

    Does Chart re-render when the button is clicked?

    mid
    const Chart = memo(function Chart({ options }: { options: { color: string } }) {
      console.log('Chart render');
      return <canvas />;
    });
    
    function Dashboard() {
      const [tick, setTick] = useState(0);
      return (
        <>
          <button onClick={() => setTick(tick + 1)}>{tick}</button>
          <Chart options={{ color: 'red' }} />
        </>
      );
    }
    1. ANo: memo skips it because the props are deeply equal to last time
    2. BNo: Chart doesn't read tick, so memo knows it's unaffected
    3. CYes: the inline object is a new reference each render, so memo's shallow check fails
    4. DYes: memo only works for class components, so it has no effect here
    Show answer

    Answer: C (Yes: the inline object is a new reference each render, so memo's shallow check fails)

    memo does a shallow comparison of props. An inline object literal is a new reference on every render of Dashboard, so the comparison fails and Chart re-renders. Hoist the constant out of the component or wrap it in useMemo.

  208. 209.

    handleClick is wrapped in useCallback and passed to <Button onClick={handleClick} />. Button is a plain function component (not wrapped in memo). What does useCallback buy you here?

    mid
    1. AEssentially nothing: Button re-renders whenever its parent does anyway
    2. BButton skips re-rendering, because its onClick prop is now stable
    3. CThe handler is created only once, so each render does much less work
    4. DIt guarantees the handler always sees the latest state values
    Show answer

    Answer: A (Essentially nothing: Button re-renders whenever its parent does anyway)

    A stable function identity only matters to something that compares it: a memo child, or a dependency array of an effect/useMemo. A non-memoized child re-renders with its parent anyway. And useCallback can actually cause stale closures if dependencies are missing; it doesn't prevent them.

  209. 210.

    App renders <ThemeContext value={{ theme }}> and re-renders because of an unrelated state change; theme is unchanged. What happens to a memo-wrapped component that calls useContext(ThemeContext)?

    hard
    1. AIt's skipped: memo prevents re-renders unless its own props change
    2. BIt's skipped: React compares context values deeply, and theme is unchanged
    3. CIt re-renders: the { theme } object is new each time, so the context value changed
    4. DOnly its children re-render; the memoized component itself is skipped
    Show answer

    Answer: C (It re-renders: the { theme } object is new each time, so the context value changed)

    Context consumers re-render whenever the provider value changes by Object.is, and memo does not stop a context-triggered render. The inline { theme } object is new every time App renders. Memoize it: const value = useMemo(() => ({ theme }), [theme]).

  210. 211.

    You click the button three times. What number does it display?

    easy
    function Clicks() {
      const clicks = useRef(0);
      return (
        <button onClick={() => { clicks.current++; }}>
          {clicks.current}
        </button>
      );
    }
    1. A3
    2. B1
    3. C0
    4. DNaN
    Show answer

    Answer: C (0)

    Mutating ref.current does not trigger a re-render, so the button keeps showing the value from the first render. The ref does hold 3 internally. Anything shown on screen should live in state.

  211. 212.

    A component renders <input value={name} /> with no onChange. What happens when the user types?

    easy
    1. AThe input updates normally and name is updated automatically
    2. BThe text doesn't change, and React warns that you provided value without an onChange handler
    3. CReact throws and unmounts the component
    4. DThe input silently becomes uncontrolled after the first keystroke
    Show answer

    Answer: B (The text doesn't change, and React warns that you provided value without an onChange handler)

    Passing value makes the input controlled: React forces the DOM value back to name on every render, so keystrokes appear to do nothing. Add onChange to update state, use defaultValue for an uncontrolled input, or readOnly if it's intentional.

  212. 213.

    Which of these errors will an error boundary catch?

    mid
    1. AAn error thrown inside a button's onClick handler
    2. BAn error thrown in a setTimeout callback
    3. CA rejected promise inside an async function called from useEffect
    4. DAn error thrown while rendering a child component
    Show answer

    Answer: D (An error thrown while rendering a child component)

    Error boundaries catch errors thrown during rendering (and in lifecycle methods) of the tree below them. Errors in event handlers and asynchronous code happen outside rendering, so you handle them with try/catch, or set state that makes a component throw during its next render.

  213. 214.

    What's wrong with this code?

    mid
    function Page() {
      const Editor = lazy(() => import('./Editor'));
      return (
        <Suspense fallback={<Spinner />}>
          <Editor />
        </Suspense>
      );
    }
    1. AEach render calls lazy again, creating a new component type, so Editor remounts and loses state
    2. BNothing: calling lazy inside the component keeps the import scoped to this page
    3. CSuspense must be placed inside Editor, not around it
    4. Dlazy only works with named exports, so the import needs .then((m) => m.Editor)
    Show answer

    Answer: A (Each render calls lazy again, creating a new component type, so Editor remounts and loses state)

    Every call to lazy returns a new component type. Calling it during render means React sees a different type each time Page renders, so it tears down and remounts Editor, resetting its state. Declare lazy components at module level; note lazy expects the module's default export.

  214. 215.

    A modal is rendered with createPortal(<button>OK</button>, document.body) from inside a <div onClick={log}>. When the button is clicked, does the div's onClick fire?

    mid
    1. ANo: the button isn't a DOM descendant of the div
    2. BOnly if the portal target is inside the div
    3. CYes: React events propagate through the React component tree, not the DOM tree
    4. DOnly for capture-phase handlers (onClickCapture)
    Show answer

    Answer: C (Yes: React events propagate through the React component tree, not the DOM tree)

    A portal changes where the DOM nodes go, but the component still lives in the same place in the React tree: it receives context from its React parents and its events bubble to React ancestors. Call e.stopPropagation() in the portal if that is unwanted.

  215. 216.

    Which of these breaks the Rules of Hooks?

    easy
    1. ACalling useState twice in a row at the top of a component
    2. BCalling useEffect inside an if (user) block
    3. CCalling use(promise) inside an if block
    4. DCalling useMemo inside a custom hook
    Show answer

    Answer: B (Calling useEffect inside an if (user) block)

    Hooks like useEffect must be called unconditionally at the top level, because React identifies them by call order between renders. Put the condition inside the effect instead. use is the documented exception: it can be called conditionally and in loops.

  216. 217.

    Sidebar and Header both call a custom hook useToggle() that wraps useState(false). Toggling in Sidebar does what to Header?

    easy
    1. ANothing: each call to a custom hook has its own independent state
    2. BHeader toggles too, because they share the same hook
    3. CHeader re-renders but keeps its value
    4. DIt throws, because a custom hook can only be used by one component
    Show answer

    Answer: A (Nothing: each call to a custom hook has its own independent state)

    Custom hooks share stateful logic, not state. Each component calling useToggle() gets its own useState slot. To share one value, lift the state up or put it in context or a store.

  217. 218.

    You wrap setQuery(e.target.value) for a controlled search <input> in startTransition to keep typing fast. What is the problem?

    hard
    1. ATransitions can't be started from event handlers, so the call is ignored
    2. BstartTransition only accepts async functions, so the update throws
    3. CTransition updates are interruptible, so the input's own value can lag behind typing
    4. DEach keystroke starts a transition that re-triggers itself: an infinite render loop
    Show answer

    Answer: C (Transition updates are interruptible, so the input's own value can lag behind typing)

    A text input needs its value updated synchronously. The recommended pattern is two pieces of state (or useDeferredValue): update the input's state normally and let the slow list render from a transition or a deferred copy of the query.

  218. 219.

    The user types "a" into an empty field. On the first re-render after the keystroke, what are the two values?

    mid
    const [query, setQuery] = useState('');
    const deferredQuery = useDeferredValue(query);
    
    return (
      <>
        <input value={query} onChange={(e) => setQuery(e.target.value)} />
        <SlowList query={deferredQuery} />   {/* SlowList is wrapped in memo */}
      </>
    );
    1. ABoth are 'a', because they update in the same render
    2. Bquery is 'a' and deferredQuery is still ''; a background render then catches up
    3. Cquery is still '' and deferredQuery is 'a', because the input is deferred
    4. DdeferredQuery only updates after a fixed ~300 ms debounce has passed
    Show answer

    Answer: B (query is 'a' and deferredQuery is still ''; a background render then catches up)

    React first re-renders urgently with the new query and the old deferred value, so the input updates immediately and the memoized SlowList is skipped. Then it renders again in the background with the new value, and that render can be interrupted by further typing. There's no fixed delay as with debouncing.

  219. 220.

    Which of these can you do directly in a React Server Component?

    mid
    1. AKeep a counter in useState and increment it on click
    2. BAttach an onClick handler to a button it renders
    3. CFetch data in useEffect after the component mounts
    4. DMake the component async and await a database query in its body
    Show answer

    Answer: D (Make the component async and await a database query in its body)

    Server Components run only on the server, so they can be async and access data sources directly, but they can't use state, effects, or event handlers. Interactive parts go into a Client Component marked with 'use client'.

  220. 221.

    Why doesn't the button ever become disabled while save is running?

    hard
    import { useFormStatus } from 'react-dom';
    
    function EditForm() {
      const { pending } = useFormStatus();
      return (
        <form action={save}>
          <input name="title" />
          <button disabled={pending}>Save</button>
        </form>
      );
    }
    1. Aaction must be a URL string; with a function, no pending state is tracked
    2. Bpending is only true for forms submitted with method="get"
    3. CThe button needs an explicit type="submit" for the status to update
    4. DuseFormStatus only reads a parent form, so it must be called inside the <form>
    Show answer

    Answer: D (useFormStatus only reads a parent form, so it must be called inside the <form>)

    useFormStatus reads the status of the form that contains the component calling it, so called in the component that renders the <form>, it never sees that form's submission. Move the button into its own SubmitButton component that calls the hook. Buttons inside a form already default to type="submit".

  221. 222.

    A parent's state changes. Its child <Footer /> receives no props and isn't wrapped in memo. Does Footer re-render?

    easy
    1. ANo: React only re-renders children whose props changed
    2. BOnly if Footer reads a context value that changed
    3. CYes: when a component renders, React renders its children too by default
    4. DOnly in development, because of StrictMode double rendering
    Show answer

    Answer: C (Yes: when a component renders, React renders its children too by default)

    By default, rendering a component re-renders its whole subtree; React doesn't check props unless the child is wrapped in memo. This is usually cheap. If it isn't, memoize the child, move the state down, or pass the child in as children from a component that doesn't re-render.

  222. 223.

    What happens when this component mounts?

    mid
    function Results({ query }: { query: string }) {
      const [data, setData] = useState<Item[]>([]);
      const options = { query, limit: 10 };
    
      useEffect(() => {
        fetchResults(options).then(setData);
      }, [options]);
    
      return <List items={data} />;
    }
    1. AIt fetches once on mount and again only when query changes
    2. BIt fetches over and over: options is a new object each render, and every setData causes another render
    3. CReact detects the object dependency and skips the effect
    4. DIt fetches once, because effects with dependencies never re-run on their own
    Show answer

    Answer: B (It fetches over and over: options is a new object each render, and every setData causes another render)

    Dependencies are compared with Object.is, and options is recreated on every render, so the effect runs after every render. Each fetch stores a new array in state, which re-renders, which re-runs the effect. Create the object inside the effect and depend on query instead.

  223. 224.

    What does the button show after two clicks?

    easy
    function Counter() {
      const [state, setState] = useState({ count: 0 });
      function handleClick() {
        state.count++;
        setState(state);
      }
      return <button onClick={handleClick}>{state.count}</button>;
    }
    1. A2
    2. B1
    3. C0
    4. DIt throws because state is frozen
    Show answer

    Answer: C (0)

    setState(state) passes the same object reference, so Object.is says nothing changed and React bails out without re-rendering; the screen keeps showing 0 even though the object was mutated. Treat state as immutable: setState({ ...state, count: state.count + 1 }).

  224. 225.

    A Profile component keeps a local draft in useState. The parent switches from user 1 to user 2 by rendering <Profile key={userId} userId={userId} />. What happens?

    mid
    1. AThe same instance receives the new userId; the draft for user 1 stays
    2. BReact unmounts the old Profile and mounts a fresh one, so all its state (and effects) start over for user 2
    3. Ckey is ignored outside of lists
    4. DReact warns that key cannot be read as a prop
    Show answer

    Answer: B (React unmounts the old Profile and mounts a fresh one, so all its state (and effects) start over for user 2)

    A different key tells React it is a different component instance, so the old one is unmounted (cleanups run) and a new one mounts with fresh state. This is the recommended way to reset state when an identity prop changes, instead of an effect that clears state. Without the key, the draft for user 1 would carry over.

  225. 226.

    What is useId intended for?

    easy
    1. AGenerating stable keys for the items of a rendered list
    2. BCreating unique ids for new records before they're saved to the database
    3. CGenerating ids for accessibility attributes that match between server and client
    4. DReading the id attribute of the component's root DOM element
    Show answer

    Answer: C (Generating ids for accessibility attributes that match between server and client)

    useId returns a stable, unique string per component instance, for attributes like htmlFor or aria-describedby. It is identical in server-rendered HTML and on the client, avoiding the hydration mismatches that Math.random() would cause. It shouldn't be used for list keys; keys should come from your data.

esc