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.
Official reference: react.dev
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.
- jsx and composition2 scenarios · 8 MCQs
- state and identity2 scenarios · 8 MCQs
- events and inputs2 scenarios · 8 MCQs
- effects and lifecycle2 scenarios · 8 MCQs
- hooks and reducers2 scenarios · 8 MCQs
- context and stores2 scenarios · 8 MCQs
- memoization and profiling2 scenarios · 8 MCQs
- concurrent rendering2 scenarios · 8 MCQs
- suspense and lazy loading2 scenarios · 8 MCQs
- errors and recovery2 scenarios · 8 MCQs
- refs and portals2 scenarios · 8 MCQs
- forms and actions2 scenarios · 8 MCQs
- fetching and caching2 scenarios · 8 MCQs
- routing and navigation2 scenarios · 8 MCQs
- ssr and hydration2 scenarios · 8 MCQs
- server components2 scenarios · 8 MCQs
- testing react2 scenarios · 8 MCQs
- react typescript2 scenarios · 8 MCQs
- accessibility2 scenarios · 8 MCQs
- security2 scenarios · 8 MCQs
- architecture and design2 scenarios · 8 MCQs
- build and delivery2 scenarios · 8 MCQs
- styling and internationalization2 scenarios · 8 MCQs
- legacy and migration2 scenarios · 8 MCQs
- practical system design2 scenarios · 8 MCQs
- 1.easy
Why can
count && <Badge />display a zero when count is zero?- AThe expression returns the number zero
- BReact converts every false value to text
- 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.easy
Why does
<profile />not call an imported function named profile?- AImports cannot be used in JSX
- BAll components must be classes
- 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.easy
A mapped item returns two sibling elements. Where should its stable key go?
- AOn the array variable
- BOn an explicit Fragment wrapping the pair
- 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.mid
In
<Button {...defaults} disabled={false} />, which disabled value wins?- AThe explicit false value
- BThe value in defaults
- 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.easy
A layout accepts a toolbar element as a prop. What pattern does this illustrate?
- AInheritance of DOM nodes
- BMutating a child component
- 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.easy
What should you do before rendering a plain user object as visible JSX content?
- AAdd a key to the object
- BSelect its display fields or format it
- 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.easy
A component returns null. What happens to its existing component state while it stays mounted?
- AThe state can remain even though it renders no DOM
- BIts state is necessarily deleted
- 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.mid
Why prefer
<Panel />to callingPanel()inside another component?- ADirect calls always compile faster
- BJSX disables Hooks inside Panel
- 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.easy
After calling a state setter, why does the current handler still read its old state variable?
- AThe setter did not run
- BReact rewrites the variable only after console.log
- 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.easy
Starting at zero, two
setCount(c => c + 1)calls in one handler produce what next count?- A0
- B2
- C1
Show answer
Answer: B (2)
Functional updaters are queued and each receives the result of the preceding update.
- 11.easy
What does
setUser({name: 'Mira'})do to other fields in an object state value?- AReplaces the whole value unless fields are explicitly preserved
- BShallow-merges all old fields automatically
- 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.mid
Which form defers an expensive state initializer until initialization?
- A
useState(createInitialState()) - B
useState(() => createInitialState) - C
useState(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.
- A
- 13.mid
A profile editor should discard its draft when the selected user changes. Which approach provides an explicit reset boundary?
- AMutate the existing draft object
- BKey the editor by the user ID
- 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.easy
How should you sort an array stored in state without mutating it?
- ASort a copy and set the new array
- BCall sort on the existing state array
- 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.easy
A total can be calculated cheaply from cart items. Where should it usually live?
- AAs duplicate state synchronized by an Effect
- BIn a module-level mutable variable
- 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.mid
Setting state to the same object reference can skip an update because React compares values using what?
- AOnly their constructor names
- BObject.is semantics
- 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.easy
Which button prop waits for a click before saving?
- A
onClick={new save()} - B
onClick={save} - C
onClick={save()}
Show answer
Answer: B (
onClick={save})Pass a function to an event prop. Calling it during render performs the work immediately.
- A
- 18.easy
In a bubbling handler, which property identifies the element whose handler is running?
- AcurrentTarget
- Btarget
- CrelatedTarget
Show answer
Answer: A (currentTarget)
target can be a nested element that originated the event; currentTarget identifies the element handling it.
- 19.easy
What prevents a normal form submission from navigating the page?
- ACalling stopPropagation only
- BReturning a string from the handler
- 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.easy
Which property should update boolean state for a controlled checkbox?
- Aevent.target.name
- Bevent.target.checked
- 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.mid
An input starts with undefined value and later receives a string. What is the likely issue?
- AIt switches from uncontrolled to controlled
- BIt automatically becomes read-only forever
- 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.mid
Why might a numeric field keep its editing value as a string?
- AReact cannot render numbers
- BString state disables validation
- 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.easy
How should a file picker normally obtain the user's selected files?
- ARender file bytes inside its value prop
- BRead its FileList after user selection
- 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.mid
Which React prop observes a click in the capture phase?
- AonClickCapture
- BonClickBefore
- ConCaptureClick
Show answer
Answer: A (onClickCapture)
Capture handlers run on the path toward the target before the usual bubbling handlers.
- 25.mid
An Effect dependency changes. What happens to its previous cleanup?
- AIt runs before the replacement setup
- BIt runs only when the browser closes
- 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.mid
An Effect depends on a new options object made every render. Why might it reconnect too often?
- AReact compares every nested field deeply
- BObjects cannot be Effect dependencies
- 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.easy
Where should a purchase request caused by a button click normally begin?
- AIn a useMemo calculation
- BIn the interaction handler or action
- 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.mid
Why should an Effect callback not directly be an async function?
- AIt returns a Promise instead of a cleanup function or nothing
- BAsync code is banned in components
- 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.mid
Two searches finish out of order. What prevents an old response replacing the latest result?
- AAlways accept whichever response arrives last
- BRemove all dependencies from the Effect
- 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.mid
A tooltip must measure layout before the browser paints a corrected position. Which Hook fits?
- AuseId
- BuseLayoutEffect
- CuseDebugValue
Show answer
Answer: B (useLayoutEffect)
Layout Effects run before repaint and can block it, so reserve them for layout-sensitive work.
- 31.easy
Does useEffect execute while producing server-rendered HTML?
- ANo, it runs on the client
- BYes, before every server template
- 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.hard
When is useEffectEvent appropriate?
- ATo remove every dependency from every Effect
- BTo create a general callback passed to children
- 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.easy
Why is useState after a conditional early return unsafe?
- AEarly returns are invalid JavaScript
- BState always becomes global
- 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.easy
Two components call the same custom state Hook. What do they share automatically?
- AA single component key
- BThe reusable logic, not the individual state instances
- 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.mid
Which work should stay outside a reducer?
- ASending an HTTP request
- BCalculating a next-state value
- 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.mid
What should an action such as
{type: 'itemRemoved', id}primarily communicate?- AEvery DOM operation required
- BA request to mutate all objects
- 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.easy
Changing ref.current does what by itself?
- AResets all state
- BDoes not request a render
- 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.mid
What is useDebugValue designed for?
- ALabeling custom Hook information in React DevTools
- BDisplaying text in the page
- 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.mid
Should useId generate keys for records in a list?
- AYes, it tracks database identity automatically
- BOnly when records can reorder
- 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.hard
How does the use API differ from ordinary Hooks regarding conditional calls?
- AIt must run only in event handlers
- BIt can read a resource inside conditions, while still requiring a component or Hook context
- 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.easy
Two providers for the same context surround a consumer. Which value does it read?
- AA merge of both values
- BThe nearest matching provider above it
- 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.easy
A provider explicitly supplies undefined. Does the consumer receive the context default?
- ANo, it receives undefined
- BYes, defaults replace all falsy values
- 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.mid
Can memo alone block an update from a context that the component consumes?
- AYes, if props are empty
- BYes, if the provider is a parent
- CNo
Show answer
Answer: C (No)
Context changes reach consumers independently of the memo comparison of props.
- 44.mid
Why can
{user, logout}created inline as a provider value cause extra consumer renders?- AFunctions are forbidden in context
- BIts object identity changes on parent renders
- 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.mid
A rapidly changing cursor position shares context with a static theme. What can reduce unrelated updates?
- ASeparate contexts by update pattern
- BAdd more fields to the same value
- 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.hard
What should getSnapshot return while an external store has not changed?
- AA fresh equivalent object on every call
- BA Promise on every call
- 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.mid
What must an external store subscription function normally return?
- AThe store's entire history
- BA function that unsubscribes
- 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.hard
Why provide getServerSnapshot for a server-rendered external-store consumer?
- ATo supply consistent server and initial hydration data
- BTo send browser event handlers to the database
- 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.easy
What does useCallback cache?
- AA function reference
- BThe function's returned value
- 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.mid
Why must a useMemo calculation be pure?
- AIt executes only on a server
- BIt is a cleanup callback
- 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.mid
A memoized child receives a new object prop on every render. What commonly happens?
- AThe child is permanently skipped
- BIts props comparison sees a changed reference
- 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.hard
A custom memo comparator ignores a changed callback prop. What can go wrong?
- AThe child keeps a callback capturing old state
- BThe callback becomes a server action
- 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.mid
What should justify introducing memoization around a component?
- AThe number of lines in its file
- BHaving any prop at all
- 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.mid
Should useMemo be relied on to hold an essential mutable connection forever?
- AOnly if it has no dependencies
- BNo, use an appropriate lifecycle-managed resource
- 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.mid
What is React Compiler intended to automate?
- AMemoization of compatible components and values
- BServer authorization
- 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.hard
What does a Profiler measurement help inspect?
- AEvery database query automatically
- BOnly source-file size
- 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.mid
Should the state directly controlling a text input be updated only as a Transition?
- AYes, to delay all keystrokes
- BOnly when typing quickly
- 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.hard
What can happen to non-urgent render work during an urgent update?
- AIt becomes a browser worker automatically
- BIt can be interrupted and restarted
- 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.mid
Does useDeferredValue by itself debounce network requests?
- ANo
- BYes, always by 300 milliseconds
- 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.mid
Which Hook provides an isPending flag for its transitions?
- AuseRef
- BuseImperativeHandle
- CuseTransition
Show answer
Answer: C (useTransition)
useTransition exposes pending state along with its startTransition function; the standalone function does not expose a flag.
- 61.hard
Does startTransition move a heavy synchronous JavaScript calculation off the main thread?
- AOnly in production
- BNo
- 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.mid
A search result list uses a deferred query. How should its temporary old results be interpreted?
- AThey may intentionally lag behind the input
- BThey necessarily prove a cache bug
- 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.hard
For versions with the documented async Transition caveat, how should setters after await be marked as transitions?
- AAssume all future timers inherit the scope
- BReplace them with direct DOM mutation
- 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.hard
Why is writing analytics during render unsafe under concurrent rendering?
- ARender always commits exactly once
- BAn abandoned render can still have performed the write
- 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.mid
What does React.lazy normally expect its loader Promise to resolve to?
- AA CSS stylesheet string
- BA module object with a default component export
- 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.mid
Where should a lazy component declaration normally live?
- AOutside rendering, at module scope
- BInside every list iteration
- 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.mid
Will a plain fetch started in useEffect automatically activate Suspense?
- AYes, every Promise activates it
- BOnly if the URL ends in JSON
- CNo
Show answer
Answer: C (No)
Suspense reacts to supported suspending resources or lazy components, not arbitrary asynchronous work in Effects.
- 68.mid
What primarily determines a useful Suspense boundary location?
- AA requirement for one boundary per DOM element
- BWhich content should reveal or load together
- 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.mid
A lazy import rejects. Which mechanism handles its render error?
- AAn appropriate Error Boundary
- BThe Suspense fallback alone
- 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.hard
Why avoid creating a fresh uncached Promise for a use read every client render?
- APromises cannot resolve to data
- Buse only accepts strings
- 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.mid
What do nested Suspense boundaries enable?
- AGuaranteed parallel database queries
- BIndependent progressive reveal of different UI regions
- 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.hard
A component suspends before its first successful mount. Should it rely on local state from that abandoned attempt being preserved?
- ANo
- BYes, every initializer is retained forever
- 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.mid
Will an Error Boundary normally catch a throw inside a click handler?
- ANo, handle interaction errors explicitly
- BYes, all JavaScript errors are caught
- 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.mid
Can an Error Boundary catch an error in its own fallback render?
- AYes, by retrying itself forever
- BOnly in development
- 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.easy
A fetch rejects in an event handler. What is an appropriate response?
- AIgnore it because the component mounted
- BCatch it and set a visible error state
- 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.mid
After a failed item detail page, why might a boundary be keyed by item ID?
- ATo reset error state when a different item is selected
- BTo authorize the item
- 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.mid
What belongs in client error reporting?
- APasswords and session cookies
- BOnly a generic success message
- 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.mid
Why put a boundary around an optional recommendation widget?
- AIt replaces all tests
- BIts failure need not remove the entire page
- 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.hard
Why is blindly rerendering a failed component in a tight loop a poor recovery strategy?
- AThe unchanged cause can trigger repeated failures
- BEvery error resolves after one rerender
- 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.easy
Should an invalid email field normally crash into an Error Boundary?
- AYes, all invalid input is an exception
- BOnly when the input is controlled
- 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.easy
When is a DOM ref normally available for imperative work?
- ABefore its first render starts
- BAs soon as the module imports
- 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.mid
Why expose a small handle such as focus through useImperativeHandle?
- ATo turn a DOM node into context
- BTo limit the imperative API a parent depends on
- 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.mid
In React 19 function components, how can a component receive a ref?
- AThrough a ref prop
- BOnly through a class constructor
- 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.mid
A button is rendered through a portal. How do its React events propagate?
- AOnly through the portal container's React siblings
- BThey never propagate
- 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.mid
Can portal content consume context from its React ancestors?
- AOnly if it is rendered twice
- BYes
- 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.mid
Does creating a portal automatically provide modal focus management?
- ANo
- BYes, including focus restoration
- 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.mid
Why can a newly created ref callback cause repeated detach and attach work?
- ACallbacks cannot reference DOM nodes
- BThe browser clones the element
- 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.hard
Why is manually deleting a React-managed child node risky?
- AReact automatically imports the deletion into state
- BReact's next commit can conflict with the mutated DOM
- 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.mid
What does useActionState primarily connect to component state?
- AThe nearest DOM ref
- BThe result of an action
- 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.mid
What is the first argument supplied to an action wrapped by useActionState?
- AThe previous action state
- BAlways the submit event
- 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.mid
Where must a useFormStatus consumer be to observe a form's status?
- AOnly in the component that returns the form above it
- BAnywhere in the same module
- 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.easy
What does a function passed to a form action receive for the submission?
- AThe entire React tree
- BFormData
- CA CSS selector
Show answer
Answer: B (FormData)
Named form controls contribute submission values; server-side validation is still required.
- 93.easy
Why does a submitted input generally need a name attribute?
- AIt supplies the field's FormData key
- BIt is required for every CSS rule
- 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.mid
What does useOptimistic support?
- AGuaranteed mutation success
- BPermanent browser caching
- 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.mid
Does using a Server Function for a form remove the need for authorization?
- AOnly for hidden inputs
- BNo
- 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.easy
Inside a form, why give a non-submit button type button?
- AIts default behavior may otherwise submit the form
- BIt enables React rendering
- 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.mid
What must a query cache key include for filtered search results?
- AParameters that change the requested result
- BOnly the component's display name
- 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.easy
Does fetch normally reject its Promise just because the server returned 404?
- AYes, all non-200 responses reject
- BOnly in React components
- 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.mid
What does passing an AbortSignal to fetch enable?
- AGuaranteeing no packets were sent
- BCanceling obsolete client request work
- 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.mid
After successfully updating an item, which cached data may need attention?
- AIts detail and relevant list queries
- BOnly unrelated user preferences
- 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.mid
What does a cache freshness window describe?
- AHow long the server guarantees truth
- BHow long React keeps a DOM node
- 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.mid
A second request requires an ID returned by the first. What is appropriate?
- AUse a random ID to parallelize them
- BStart it once the required ID exists
- 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.mid
Why deduplicate identical in-flight reads?
- ATo avoid duplicate network work for the same resource
- BTo bypass response validation
- 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.easy
Why distinguish an empty result from a loading state?
- ABoth states always require a spinner
- BEmpty arrays cannot be rendered
- 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.easy
Which state is often worth putting in the URL?
- AA user's password
- BAn uncommitted private access token
- 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.easy
For ordinary navigation, why prefer a link element over a clickable div?
- AIt guarantees server permission
- BIt supplies browser navigation and keyboard semantics
- 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.mid
How should an item ID read from a route be treated?
- AAs untrusted input requiring validation and authorization
- BAs already authorized by the router
- 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.mid
Can a client-side protected-route component secure an API by itself?
- AYes, if it redirects quickly
- BOnly if its component is memoized
- CNo
Show answer
Answer: C (No)
Client guards improve navigation experience; the API must enforce access independently.
- 109.mid
What is a common benefit of nested route layouts?
- ARoutes no longer need URLs
- BShared UI can remain while child content changes
- 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.mid
Changing sort order while on page 12 may require what?
- AResetting or validating the current page
- BDeleting browser history
- 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.easy
How should an unmatched route normally be handled?
- AShow an indefinite loading spinner
- BTreat it as a successful empty dashboard
- 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.mid
What is a trade-off of prefetching route data?
- AIt always reduces transferred bytes
- BFaster navigation can consume bandwidth for unused routes
- 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.easy
Which API attaches React to HTML already rendered for the same tree?
- AcreateContext
- BhydrateRoot
- CcreatePortal
Show answer
Answer: B (hydrateRoot)
Hydration reuses server-rendered markup and expects the initial client output to match it.
- 114.mid
Why can rendering Date.now during both server and initial client rendering cause a warning?
- AThe generated text can differ
- BDates are invalid React children
- 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.easy
Why does reading window during server rendering fail?
- AReact never allows window access
- BJSX converts window to a prop
- 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.mid
What is suppressHydrationWarning intended for?
- ADisabling all client rendering
- BA narrow unavoidable mismatch escape hatch
- 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.mid
What can streaming server rendering improve?
- ADelivery of ready HTML while other regions wait
- BThe correctness of every API permission
- 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.hard
Why is mutable module-level per-user state dangerous on a server?
- AEvery request necessarily gets a new process
- BModules are inaccessible to server code
- 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.mid
Does seeing server-rendered markup prove its click handlers are ready?
- AOnly for buttons
- BNo
- CYes, markup contains executable event handlers
Show answer
Answer: B (No)
Visible HTML and hydrated interactivity are different stages; design loading behavior accordingly.
- 120.mid
How can invalid HTML nesting contribute to hydration failures?
- AThe browser may repair the markup into a different tree
- BIt prevents all JavaScript downloads
- 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.mid
What does a use client directive primarily establish in an RSC-compatible system?
- AA client module boundary
- BA guarantee the module never participates in server prerendering
- 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.mid
Where should a database credential used by a Server Component remain?
- AIn props passed to a Client Component
- BIn a hidden DOM field
- 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.mid
Which capability belongs in a Client Component rather than a Server Component?
- AProducing noninteractive markup
- BInteractive useState-driven input
- 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.mid
Does use server mark a component as a Server Component?
- ANo, it marks Server Functions
- BYes, in every React application
- 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.mid
What constraint applies to values crossing an RSC server-to-client boundary?
- AAny live database connection can cross
- BEvery value must be a plain string
- 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.hard
Why is moving a secret-bearing module under use client dangerous?
- AIt only changes CSS ordering
- BIt may enter the client dependency graph
- 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.mid
How should a Server Function treat an ID supplied by the client?
- AValidate it and authorize the operation
- BTrust it because React encoded it
- 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.hard
Are Server Components and server rendering to HTML the same mechanism?
- AYes, they are interchangeable names
- BOnly when no CSS is used
- 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.easy
Why query a rendered button by role and accessible name?
- AIt checks the private Hook array
- BIt avoids rendering the component
- 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.mid
A message appears after an async request. What should the test do?
- ASleep for a fixed minute
- BAwait an appropriate appearance query
- 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.mid
What does act help ensure in React tests?
- ARelevant updates are processed before assertions
- BNetwork calls never occur
- 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.easy
Why simulate a realistic click rather than invoke a component's private handler directly?
- AIt skips event propagation
- BIt guarantees visual layout
- 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.mid
What is a limitation of a large snapshot test?
- AIt replaces error-state tests
- BIt may pass while behavior or accessibility is wrong
- 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.mid
A component uses routing hooks. What must its test normally supply?
- AAn appropriate router environment
- BA random context provider
- 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.mid
What should tests with fake timers do during cleanup?
- ALeave the fake clock active for later tests
- BDelete all state modules
- 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.mid
Where is a useful place to mock data fetching for an integrated component test?
- ABy removing all loading UI
- BAt the network boundary
- 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.mid
What type design can require href for a link variant but not a button variant?
- AAn untyped any prop
- BA discriminated union of props
- 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.mid
Why can currentTarget be easier to type for an input handler than target?
- AIt corresponds to the element handling the event
- BIt always contains a string
- 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.easy
A state value starts null and later holds a User. What annotation expresses this?
- AOnly null
- BAny by default
- 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.easy
Why must a DOM ref type generally allow null?
- AAll refs store JSON
- BThe element is absent before mount and after removal
- 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.mid
Which React type commonly represents content accepted as children?
- AReactNode
- BCSSProperties
- CDispatch
Show answer
Answer: A (ReactNode)
ReactNode covers renderable values; narrower types can be appropriate when the component intentionally restricts its content.
- 142.mid
How can a wrapper button preserve native button prop types?
- AManually type every prop as string
- BUse only an index signature of any
- 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.mid
Does asserting a JSON response as User validate it at runtime?
- AOnly in strict mode
- BNo
- 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.hard
What can an exhaustive action switch detect?
- AA newly added action missing reducer handling
- BEvery possible network error
- 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.easy
An icon-only button needs what for assistive technology?
- AAn accessible name
- BOnly a tooltip visible on hover
- 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.easy
What connects a label to a separate input in JSX?
- AThe label's className
- BIdentical placeholder text
- 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.mid
How can a non-focus-changing async status be announced?
- ARenaming the component file
- BAn appropriately configured live region
- 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.mid
Do stable React keys provide visible or accessible labels automatically?
- ANo
- BYes, screen readers read every key
- COnly for numeric keys
Show answer
Answer: A (No)
Keys are internal identity information and do not replace semantic names, labels or content.
- 149.mid
Does aria-disabled alone prevent a link or button's action?
- AYes, the browser cancels all events
- BOnly in production
- CNo
Show answer
Answer: C (No)
ARIA communicates semantics. You must also implement the intended interaction behavior and consider focus requirements.
- 150.mid
How can a field expose its error message programmatically?
- ARemove its label
- BAssociate error text using an appropriate description and invalid state
- 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.
- 151.easy
What preference should an animated React interface respect?
- Aprefers-reduced-motion
- BThe alphabetic order of classes
- 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.
- 152.mid
Why avoid positive tabIndex values as a general focus strategy?
- AThey make all elements semantic buttons
- BThey are required for every modal
- 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.
- 153.easy
How does React normally render an untrusted string child containing markup?
- AAs executable HTML
- BAs a component import
- 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.
- 154.mid
What is required before injecting untrusted rich HTML?
- AReplacing spaces
- BA suitable sanitization policy at a trusted boundary
- 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.
- 156.mid
What should you assume about an environment value embedded in a browser bundle?
- AIt is encrypted by the build
- BIt is visible only to React
- 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.
- 157.mid
Why does storing a token in localStorage not protect it from same-origin script compromise?
- AReact encrypts its keys
- BJavaScript on the origin can read it
- 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.
- 158.mid
What should a user-supplied navigation URL be checked against?
- AAllowed schemes and destinations as appropriate
- BOnly its string length
- 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.
- 159.mid
Cookie-authenticated mutations may need which server-side protection?
- AA React key
- BA client-only disabled button
- 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.
- 160.mid
What helps manage frontend dependency risk?
- ACopying credentials into lockfiles
- BReviewing updates and maintaining a dependency inventory
- 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.
- 161.easy
Two sibling widgets must edit the same selection. Where should its shared source of truth normally be?
- AA random DOM attribute
- BTheir closest suitable common owner
- 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.
- 162.mid
What is a useful criterion for a feature module boundary?
- AA cohesive user capability and its contracts
- BAn arbitrary number of files
- 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.
- 163.mid
What should a shared design-system component prioritize?
- AEvery product-specific network request
- BHidden global business state
- 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.
- 164.mid
What does a headless component or Hook typically separate?
- ATypeScript from JavaScript
- BBehavior from visual rendering
- 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.
- 165.mid
What makes a reusable component externally controlled?
- AIts authoritative value and update request come through props
- BIt never rerenders
- 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.
- 167.mid
Why keep a domain rule such as order eligibility outside a presentational button?
- AReact automatically enforces domain rules
- BIt can be reused and verified at appropriate boundaries
- 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.
- 168.hard
What is a cost of splitting one UI into independently deployed microfrontends?
- ACoordination of shared contracts, routing and dependencies
- BAutomatic elimination of integration bugs
- 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.
- 169.mid
What helps a bundler remove unused code?
- AAnalyzable module exports and accurate side-effect information
- BImporting the entire library into a global
- 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.
- 170.mid
What commonly creates an asynchronous bundle boundary?
- AAn ordinary function call
- BA CSS class name
- 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.
- 171.mid
Why retain usable source maps for production error diagnosis under a deliberate access policy?
- AThey encrypt browser code
- BThey map transformed stack traces to original code
- 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.
- 172.mid
Why use content-hashed asset filenames?
- AChanged content receives a different cacheable URL
- BThey authenticate users
- 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.
- 173.mid
A small screen downloads a large JavaScript bundle. What is a useful first investigation?
- AAdd memo to every component
- BIncrease the page's font size
- 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.
- 174.mid
If configuration is compiled into static JavaScript, does changing a server environment variable necessarily update it?
- AOnly on Tuesdays
- BNo, a rebuild or explicit runtime configuration path may be needed
- 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.
- 175.mid
Why compare performance using a suitable production or profiling build?
- ADevelopment checks and tooling alter costs
- BProduction never has bugs
- 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.
- 176.hard
What should be tested when lazy components load their own styles?
- AOnly the component filename
- BWhether CSS has React keys
- 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.
- 177.easy
What do CSS Modules primarily provide?
- AAutomatic translation of text
- BServer-side form validation
- 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.
- 178.easy
For many length-valued inline style properties, what does React do with numeric values?
- ARejects all numbers
- BAdds pixel units where appropriate
- 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.
- 179.mid
What can combine semantic theme state with efficient styling?
- AA theme setting that selects CSS variables
- BDuplicating every component for each color
- 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.
- 180.mid
Which styling approach helps adapt layouts to right-to-left languages?
- AHardcoding left for every leading edge
- BReversing every string
- 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.
- 181.mid
Why avoid building plural messages by simply appending s?
- AEvery language has exactly two plural forms
- BPlural rules vary across languages
- 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.
- 182.mid
What should determine user-visible date formatting?
- AAn explicit locale and time-zone policy
- BThe developer's laptop settings only
- 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.
- 183.mid
Why are complete translated messages preferable to concatenated fragments?
- ATranslation files cannot contain variables
- BReact sorts words alphabetically
- 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.
- 184.mid
What helps avoid content jumping when images load?
- ADelay all text until the image loads
- BReserve space using dimensions or aspect ratio
- 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.
- 185.mid
How does class setState with an object differ from a Hook state setter?
- AHook setters shallow-merge but class setters replace
- BClass setState shallow-merges the partial state
- 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.
- 186.mid
What often replaces componentWillUnmount cleanup when migrating subscriptions to Hooks?
- AThe cleanup returned by an Effect
- BA useMemo return value
- 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.
- 187.mid
What is a suitable direction when migrating legacy string refs?
- AMove ref names into CSS selectors
- BKeep them as authentication IDs
- 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.
- 188.mid
In React 19, what should replace reliance on removed findDOMNode behavior?
- AA global query for every div
- BAn explicit ref to the relevant DOM element
- 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.
- 189.easy
What replaces ReactDOM.render in a modern client-only root?
- AcreateRoot followed by root.render
- BhydrateRoot for every empty container
- 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.
- 190.mid
What comparison does PureComponent use for class props and state?
- ARecursive database equality
- BA comparison of rendered pixels
- CShallow comparison
Show answer
Answer: C (Shallow comparison)
Immutable updates matter because shallow comparisons cannot detect nested mutation behind the same reference.
- 191.mid
What should a higher-order component generally preserve?
- AOnly its filename
- BThe wrapped component's intended prop contract
- 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.
- 192.mid
What is a render prop?
- AA function prop used to supply rendered content
- BA browser method that edits a DOM node
- 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.
- 193.mid
An autocomplete returns old suggestions after rapid typing. What invariant is missing?
- AResults must belong to the active query
- BEvery response must be displayed
- 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.
- 194.mid
A chat reconnect replays previously received messages. How should the UI deduplicate?
- ABy displayed timestamp text alone
- BBy array position
- 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.
- 195.mid
Why separate uploading from server processing in a file workflow?
- AReact cannot show multiple statuses
- BTransfer completion need not mean the file is ready
- 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.
- 196.mid
When reordering editable cards, what should their keys follow?
- AThe cards' stable IDs
- BTheir current array indices
- 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.
- 197.mid
What information can support a reliable local undo operation?
- AOnly the button's color
- BA random timeout
- 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.
- 198.mid
What prevents a burst of notifications from overwhelming a screen reader?
- ARemoving all text labels
- BA deliberate announcement and queue policy
- 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.
- 199.hard
What constrains data sent to a Web Worker for heavy computation?
- ASupported structured-clone or transferable values
- BReact props syntax alone
- 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.
- 200.hard
How can an editor detect that its saved record changed on the server?
- AAssume the last opened tab owns the record
- BCompare only the local component key
- 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.
- 201.mid
You type something into each of the three uncontrolled inputs, then click "Remove first". What do you see?
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> ))} </> ); }- ARows b and c remain, each still showing the text you typed next to them
- BAll remaining inputs are cleared because the list re-rendered
- CLabels b and c remain, but their inputs show the text typed for a and b; the text typed for c is gone
- 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}, keys0and1still exist after the deletion, so React reuses those two DOM rows (including the uncontrolled input values) and removes the row with key2. 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. - 202.easy
What does the button show after one click?
function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 1); setCount(count + 1); } return <button onClick={handleClick}>{count}</button>; }- A3
- B1
- C0
- DIt flashes 1, 2, 3 and settles on 3
Show answer
Answer: B (1)
countis a snapshot: it is0for 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 formsetCount(c => c + 1). - 203.hard
Starting from
n = 0, what isnafter one click?const [n, setN] = useState(0); function handleClick() { setN((x) => x + 1); setN(n + 5); setN((x) => x * 2); }- A2
- B12
- C5
- D10
Show answer
Answer: D (10)
React processes the queue in order:
x => x + 1gives 1, thensetN(n + 5)replaces it with0 + 5(the snapshot value ofnis 0), thenx => x * 2doubles 5 to 10. A plain value replaces whatever is queued before it; an updater function receives the result of the previous step. - 204.easy
namestarts as'Ada'. What does the click handler log?const [name, setName] = useState('Ada'); function handleClick() { setName('Grace'); console.log(name); }- A'Ada'
- B'Grace'
- Cundefined
- 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
namewill be'Grace'. The running handler closed over the old snapshot, so it logs'Ada'every time. - 205.mid
The component is rendered inside
<StrictMode>in development. What is logged on mount?function ChatRoom() { useEffect(() => { console.log('connect'); return () => console.log('disconnect'); }, []); return <h1>Chat</h1>; }- Aconnect
- Bconnect, connect
- Cconnect, disconnect, connect
- 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. - 206.hard
In what order are the effects logged when
Parentmounts?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 />; }- Aparent layout, child layout, parent effect, child effect
- Bchild layout, parent layout, child effect, parent effect
- Cchild layout, child effect, parent layout, parent effect
- 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.
- 207.mid
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?
- AIn
useEffect - BDuring render, via
ref.current.getBoundingClientRect() - CIn
useMemowith the anchor as a dependency - DIn
useLayoutEffect
Show answer
Answer: D (In
useLayoutEffect)useLayoutEffectruns 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.useEffectusually runs after paint, causing a visible flicker, and reading refs during render is unreliable because the DOM may not be updated yet. - AIn
- 208.mid
Does
Chartre-render when the button is clicked?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' }} /> </> ); }- ANo: memo skips it because the props are deeply equal to last time
- BNo: Chart doesn't read
tick, so memo knows it's unaffected - CYes: the inline object is a new reference each render, so memo's shallow check fails
- 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)
memodoes a shallow comparison of props. An inline object literal is a new reference on every render ofDashboard, so the comparison fails andChartre-renders. Hoist the constant out of the component or wrap it inuseMemo. - 209.mid
handleClickis wrapped inuseCallbackand passed to<Button onClick={handleClick} />.Buttonis a plain function component (not wrapped inmemo). What doesuseCallbackbuy you here?- AEssentially nothing: Button re-renders whenever its parent does anyway
- BButton skips re-rendering, because its
onClickprop is now stable - CThe handler is created only once, so each render does much less work
- 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
memochild, or a dependency array of an effect/useMemo. A non-memoized child re-renders with its parent anyway. AnduseCallbackcan actually cause stale closures if dependencies are missing; it doesn't prevent them. - 210.hard
Apprenders<ThemeContext value={{ theme }}>and re-renders because of an unrelated state change;themeis unchanged. What happens to amemo-wrapped component that callsuseContext(ThemeContext)?- AIt's skipped: memo prevents re-renders unless its own props change
- BIt's skipped: React compares context values deeply, and
themeis unchanged - CIt re-renders: the
{ theme }object is new each time, so the context value changed - 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, andmemodoes not stop a context-triggered render. The inline{ theme }object is new every timeApprenders. Memoize it:const value = useMemo(() => ({ theme }), [theme]). - 211.easy
You click the button three times. What number does it display?
function Clicks() { const clicks = useRef(0); return ( <button onClick={() => { clicks.current++; }}> {clicks.current} </button> ); }- A3
- B1
- C0
- DNaN
Show answer
Answer: C (0)
Mutating
ref.currentdoes 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. - 212.easy
A component renders
<input value={name} />with noonChange. What happens when the user types?- AThe input updates normally and
nameis updated automatically - BThe text doesn't change, and React warns that you provided
valuewithout anonChangehandler - CReact throws and unmounts the component
- DThe input silently becomes uncontrolled after the first keystroke
Show answer
Answer: B (The text doesn't change, and React warns that you provided
valuewithout anonChangehandler)Passing
valuemakes the input controlled: React forces the DOM value back tonameon every render, so keystrokes appear to do nothing. AddonChangeto update state, usedefaultValuefor an uncontrolled input, orreadOnlyif it's intentional. - AThe input updates normally and
- 213.mid
Which of these errors will an error boundary catch?
- AAn error thrown inside a button's
onClickhandler - BAn error thrown in a
setTimeoutcallback - CA rejected promise inside an async function called from
useEffect - 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.
- AAn error thrown inside a button's
- 214.mid
What's wrong with this code?
function Page() { const Editor = lazy(() => import('./Editor')); return ( <Suspense fallback={<Spinner />}> <Editor /> </Suspense> ); }- AEach render calls
lazyagain, creating a new component type, so Editor remounts and loses state - BNothing: calling
lazyinside the component keeps the import scoped to this page - C
Suspensemust be placed insideEditor, not around it - D
lazyonly works with named exports, so the import needs.then((m) => m.Editor)
Show answer
Answer: A (Each render calls
lazyagain, creating a new component type, so Editor remounts and loses state)Every call to
lazyreturns a new component type. Calling it during render means React sees a different type each timePagerenders, so it tears down and remountsEditor, resetting its state. Declare lazy components at module level; notelazyexpects the module's default export. - AEach render calls
- 215.mid
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'sonClickfire?- ANo: the button isn't a DOM descendant of the div
- BOnly if the portal target is inside the div
- CYes: React events propagate through the React component tree, not the DOM tree
- 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. - 216.easy
Which of these breaks the Rules of Hooks?
- ACalling
useStatetwice in a row at the top of a component - BCalling
useEffectinside anif (user)block - CCalling
use(promise)inside anifblock - DCalling
useMemoinside a custom hook
Show answer
Answer: B (Calling
useEffectinside anif (user)block)Hooks like
useEffectmust be called unconditionally at the top level, because React identifies them by call order between renders. Put the condition inside the effect instead.useis the documented exception: it can be called conditionally and in loops. - ACalling
- 217.easy
SidebarandHeaderboth call a custom hookuseToggle()that wrapsuseState(false). Toggling inSidebardoes what toHeader?- ANothing: each call to a custom hook has its own independent state
- BHeader toggles too, because they share the same hook
- CHeader re-renders but keeps its value
- 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 ownuseStateslot. To share one value, lift the state up or put it in context or a store. - 218.hard
You wrap
setQuery(e.target.value)for a controlled search<input>instartTransitionto keep typing fast. What is the problem?- ATransitions can't be started from event handlers, so the call is ignored
- B
startTransitiononly accepts async functions, so the update throws - CTransition updates are interruptible, so the input's own value can lag behind typing
- 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. - 219.mid
The user types "a" into an empty field. On the first re-render after the keystroke, what are the two values?
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 */} </> );- ABoth are 'a', because they update in the same render
- B
queryis 'a' anddeferredQueryis still ''; a background render then catches up - C
queryis still '' anddeferredQueryis 'a', because the input is deferred - D
deferredQueryonly updates after a fixed ~300 ms debounce has passed
Show answer
Answer: B (
queryis 'a' anddeferredQueryis still ''; a background render then catches up)React first re-renders urgently with the new
queryand the old deferred value, so the input updates immediately and the memoizedSlowListis 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. - 220.mid
Which of these can you do directly in a React Server Component?
- AKeep a counter in
useStateand increment it on click - BAttach an
onClickhandler to a button it renders - CFetch data in
useEffectafter the component mounts - DMake the component
asyncandawaita database query in its body
Show answer
Answer: D (Make the component
asyncandawaita database query in its body)Server Components run only on the server, so they can be
asyncand 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'. - AKeep a counter in
- 221.hard
Why doesn't the button ever become disabled while
saveis running?import { useFormStatus } from 'react-dom'; function EditForm() { const { pending } = useFormStatus(); return ( <form action={save}> <input name="title" /> <button disabled={pending}>Save</button> </form> ); }- A
actionmust be a URL string; with a function, no pending state is tracked - B
pendingis only true for forms submitted withmethod="get" - CThe button needs an explicit
type="submit"for the status to update - D
useFormStatusonly reads a parent form, so it must be called inside the<form>
Show answer
Answer: D (
useFormStatusonly reads a parent form, so it must be called inside the<form>)useFormStatusreads 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 ownSubmitButtoncomponent that calls the hook. Buttons inside a form already default totype="submit". - A
- 222.easy
A parent's state changes. Its child
<Footer />receives no props and isn't wrapped inmemo. DoesFooterre-render?- ANo: React only re-renders children whose props changed
- BOnly if
Footerreads a context value that changed - CYes: when a component renders, React renders its children too by default
- 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 aschildrenfrom a component that doesn't re-render. - 223.mid
What happens when this component mounts?
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} />; }- AIt fetches once on mount and again only when
querychanges - BIt fetches over and over:
optionsis a new object each render, and everysetDatacauses another render - CReact detects the object dependency and skips the effect
- DIt fetches once, because effects with dependencies never re-run on their own
Show answer
Answer: B (It fetches over and over:
optionsis a new object each render, and everysetDatacauses another render)Dependencies are compared with
Object.is, andoptionsis 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 onqueryinstead. - AIt fetches once on mount and again only when
- 224.easy
What does the button show after two clicks?
function Counter() { const [state, setState] = useState({ count: 0 }); function handleClick() { state.count++; setState(state); } return <button onClick={handleClick}>{state.count}</button>; }- A2
- B1
- C0
- DIt throws because state is frozen
Show answer
Answer: C (0)
setState(state)passes the same object reference, soObject.issays 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 }). - 225.mid
A
Profilecomponent keeps a local draft inuseState. The parent switches from user 1 to user 2 by rendering<Profile key={userId} userId={userId} />. What happens?- AThe same instance receives the new
userId; the draft for user 1 stays - BReact unmounts the old Profile and mounts a fresh one, so all its state (and effects) start over for user 2
- C
keyis ignored outside of lists - DReact warns that
keycannot 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
keytells 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. - AThe same instance receives the new
- 226.easy
What is
useIdintended for?- AGenerating stable keys for the items of a rendered list
- BCreating unique ids for new records before they're saved to the database
- CGenerating ids for accessibility attributes that match between server and client
- DReading the
idattribute of the component's root DOM element
Show answer
Answer: C (Generating ids for accessibility attributes that match between server and client)
useIdreturns a stable, unique string per component instance, for attributes likehtmlFororaria-describedby. It is identical in server-rendered HTML and on the client, avoiding the hydration mismatches thatMath.random()would cause. It shouldn't be used for list keys; keys should come from your data.
No questions match these filters. Try a different subtopic or clear the filters.