React Mid
How does useRef differ from useState, and when should you use a ref instead of state?
Select the correct answer
A ref stores a mutable value that persists without causing a re-render when changed.
A ref behaves like state but is reserved only for storing DOM node elements.
A ref triggers a synchronous re-render the moment its current value is updated.
A ref stores derived state that recomputes automatically whenever its dependencies change.
Explain the difference between a controlled and an uncontrolled component, and in what scenario would you prefer an uncontrolled component?
Select the correct answer
Controlled inputs cannot be validated live; uncontrolled inputs always re-render the whole form tree on input.
Controlled inputs are driven by React state; uncontrolled inputs keep value in the DOM, useful for file inputs.
Controlled inputs need no event handlers; uncontrolled inputs require an onChange on every keystroke typed.
Controlled inputs keep value in the DOM; uncontrolled inputs are driven by state, useful for live validation.
When would you choose useReducer over useState, and what are the architectural trade-offs?
Select the correct answer
When you need asynchronous state updates that automatically batch network requests for you.
When state logic is complex with many sub-values or transitions, centralizing updates in one reducer.
When state must be shared globally across the entire app without passing any props at all.
When a component has only a single boolean value that toggles between two simple states.
Why must state be treated as immutable in React, and what happens if you mutate state directly instead of using a setter function?
Select the correct answer
React freezes all state objects; mutating directly throws a runtime error that stops the tree.
React compares references to detect changes; mutating directly skips re-renders and shows stale UI.
React deep-compares every object; mutating directly causes infinite re-render loops that crash the app.
React batches mutations automatically; mutating directly only delays the re-render until the next tick.
How does React handle state updates that are dependent on the previous state, and why is the functional update pattern preferred?
Select the correct answer
Pass the previous state as a second argument, which React merges with the new value automatically.
Pass an updater function receiving the previous state, ensuring correctness when updates are batched.
Pass a function returning a promise, ensuring updates resolve in order before the next render.
Pass the new value directly, which React always reads from the freshest state during batching.
What happens if you update state inside a render function or the body of a function component?
Select the correct answer
It schedules the update for the next tick, so the current render completes with stale data.
It triggers an infinite loop of re-renders, and React throws a 'too many re-renders' error.
It silently ignores the update because state setters only work inside event handlers and effects.
It updates state once but skips the next render, leaving the component showing the old value.
How do you decide whether a piece of data should be managed as state or passed as props, and what are the conceptual trade-offs?
Select the correct answer
Use state for data a component owns and changes over time; use props to pass that data down to children
Use state for data passed from parents and props for any data that a single component owns internally over time
Use props for data that changes often and state for static data, because props re-render faster than state ever can
Use state only for primitives and props only for objects, since props cannot hold mutable primitive values safely
What is the difference between a callback ref and a ref object created with useRef, and when would you use a callback ref?
Select the correct answer
A callback ref is a function React calls with the node on attach/detach; use it to run logic when the node changes
A callback ref stores its value on the .current key; use it to avoid re-renders when state changes
A callback ref only works on class components; use it when you cannot call the useRef hook safely
A callback ref returns a frozen node snapshot; use it whenever you need to read measurements that never update again
What are Synthetic Events in React, and why does React use its own event system instead of native browser events?
Select the correct answer
A cross-browser wrapper over native events that normalizes behavior and enables consistent, efficient event handling
A separate event queue that replaces the DOM entirely so events never reach the underlying native browser elements
A logging layer that records every native event for debugging but otherwise behaves identically to raw browser events
A polyfill that adds new event types missing from older browsers while leaving existing native events fully untouched
Why does React favor composition over inheritance, and what does a compositional architecture look like?
Select the correct answer
Components are merged at build time into a single class, which reduces the runtime overhead of nested render trees
Components extend a shared base class to inherit behavior, which keeps reuse centralized and easier to reason about
Components are combined via props and children to reuse behavior, which is more flexible than class hierarchies
Components inherit state through context providers, which lets children override any parent method when it is needed
What are "Pure Components" and how do they relate to functional programming?
Select the correct answer
Components that re-render only when props or state change by shallow comparison
Components that avoid using state entirely and rely solely on context values
Components that automatically memoize all of their child components recursively
Components that never re-render after the first mount regardless of any change
What is the primary benefit of a custom hook over a standard helper function, and how do they interact with React's stateful logic?
Select the correct answer
They can call other hooks to encapsulate and reuse stateful logic, which ordinary helper functions are not allowed to do.
They isolate logic into separate files so the bundle splits cleanly, but they share the exact capabilities of helper functions.
They automatically re-render every consuming component on change, whereas helper functions must trigger updates manually via state.
They run faster than helpers because React memoizes them automatically and caches their return values between every render.
Why can't you use async functions directly inside a useEffect?
Select the correct answer
An async function blocks the main thread, but useEffect must run synchronously right after the browser paints the screen.
An async function loses access to props, but useEffect requires the callback to close over the latest state and prop values.
An async function cannot use await inside, but useEffect needs awaited calls to schedule the cleanup correctly.
An async function returns a Promise, but useEffect expects the return to be a cleanup function or undefined.
What are the main lifecycle methods of a class component, and what are their equivalents using Hooks in a function component?
Select the correct answer
componentDidMount maps to useState, componentDidUpdate to useMemo, and unmount to useCallback cleanup.
componentDidMount, componentDidUpdate, and componentWillUnmount map to a single useEffect with a dependency array and cleanup.
componentDidUpdate maps to useLayoutEffect only, while mount and unmount logic must stay in a separate class wrapper.
render maps to useEffect, componentDidMount to useRef, and unmount to a cleanup passed into useState.
What is the purpose of the cleanup function returned from useEffect, and when exactly does React run it?
Select the correct answer
It batches pending state updates together; React runs it after every render but just before the browser paints the screen.
It tears down side effects like subscriptions; React runs it before the next effect run and when the component unmounts.
It resets the component's state to initial values; React runs it once immediately after the very first render completes.
It memoizes the effect's computed result for reuse; React runs it only when the dependency array values stay the same.
What are the Rules of Hooks, and why does React enforce that hooks are called at the top level in the same order every render?
Select the correct answer
Call hooks only inside effects and handlers; React tracks each hook's state by the component's position within the tree.
Call hooks only at the top level and from React functions; React tracks each hook's state by its call order across renders.
Call hooks inside conditionals to skip unneeded ones; React tracks each hook's state by a unique key that you pass to it.
Call hooks in any order you prefer; React tracks each hook's state by the variable name you assign its returned value to.
What is the difference between useMemo and useCallback, and when is it over-optimization to use them?
Select the correct answer
useMemo caches a computed value while useCallback caches a function; using them for cheap work adds overhead, not speed.
useMemo caches a function while useCallback caches a value; using them everywhere guarantees fewer renders and is always worth it.
useMemo caches API responses while useCallback caches handlers; using them on primitives stops React from re-rendering at all.
useMemo caches a component while useCallback caches its props; using them sparingly is risky because stale values leak into children.
Explain the concept of code splitting in React using React.lazy and Suspense, and how does it improve Time to Interactive?
Select the correct answer
They cache rendered HTML on the server so the client skips hydration entirely on the first load.
They precompile all components into one bundle so the browser parses everything faster during startup.
They run component code inside a web worker so the main thread stays free during initial render.
They split bundles so components load on demand, shrinking the initial download and reducing Time to Interactive.
How does React.memo work, and how does it differ from useMemo?
Select the correct answer
React.memo caches event handlers between renders; useMemo caches the component's children element tree.
React.memo memoizes a value across renders; useMemo memoizes a component's output between mounts.
React.memo deep-compares state for updates; useMemo shallow-compares props to decide on re-rendering.
React.memo memoizes a whole component to skip re-renders; useMemo memoizes a computed value inside one.
How does React.memo optimize performance, and what is the difference between a shallow comparison and a deep comparison in this context?
Select the correct answer
React.memo re-renders on any prop change; shallow and deep comparisons both apply to hook dependencies.
React.memo performs a deep prop comparison by default; a shallow comparison only checks primitive props.
React.memo compares previous and next state deeply; shallow comparison is used only for context values.
React.memo skips re-renders via a shallow prop comparison; a deep comparison checks nested values too.
How do you identify a performance bottleneck in a React application?
Select the correct answer
Profile with the React DevTools Profiler and browser performance tools to find slow or frequent renders.
Add console logs to every render and measure how long the browser tab takes to fully load once.
Increase the production bundle size limit until the warning disappears and the app stops re-rendering.
Count the number of components on screen, since render time grows directly with total component count.
What is virtualization (or windowing), and why is it necessary for rendering large datasets?
Select the correct answer
It splits the dataset across web workers so each chunk renders on a separate background thread.
It preloads the entire dataset into memory so scrolling never triggers any additional network requests.
It compresses list items into a single canvas element, reducing the total number of React components.
It renders only the items currently visible in the viewport, avoiding DOM nodes for off-screen data.
When is the Context API the right choice versus simply drilling props, and what are the performance pitfalls of overusing Context?
Select the correct answer
Use Context for widely-shared, stable data; overusing it re-renders all consumers on any change
Use Context only at the root level; overusing it duplicates state and desyncs the consumer values
Use Context for frequently changing data; overusing it caches values and prevents needed updates
Use Context for deeply nested local state; overusing it blocks parent components from re-rendering
What is the Context API, and does it replace a dedicated state management library?
Select the correct answer
Context only works for theming and locale, so a library is always required for any other shared state
Context is a complete state manager that fully replaces Redux, including middleware and devtools
Context stores global state in a single store and re-renders only the components that subscribe to it
Context shares data through the tree but doesn't manage or optimize state like a dedicated library
What are Error Boundaries, why can they only be implemented as Class Components, and what types of errors do they not catch?
Select the correct answer
Components that catch render errors below them; only classes work since no Hook exists, and event handler and async errors slip through.
Components that catch errors at build time; only classes work since they predate Hooks, and errors in child lifecycle methods are missed entirely.
Components that catch every runtime error globally; only classes work since functions cannot hold state, and event handler errors are included.
Components that catch network and async errors; only classes work since Hooks cannot be conditional, and render-phase errors slip through entirely.
When would you use ReactDOM.createPortal, and can you explain a scenario where the DOM hierarchy needs to differ from the React component hierarchy?
Select the correct answer
To render children on the server first so that hydration of nested overlays happens before the rest of the page tree.
To render children into a separate React root so that their state is fully isolated from the parent application tree.
To render children into a DOM node outside the parent, like a modal that must escape an overflow or z-index constraint.
To render children lazily into a hidden node so that expensive subtrees mount only when the parent becomes visible.
What are "Higher-Order Components" (HOCs) and why have they become less common since the introduction of Hooks?
Select the correct answer
A component that renders another component lazily; Hooks now share logic by deferring all rendering until the data has resolved.
A function that takes a component and returns an enhanced one; Hooks now share logic without wrapper nesting or prop collisions.
A class that extends another component's behavior; Hooks now share logic by letting functions inherit from parent components directly.
A function that merges several components into one; Hooks now share logic by combining their render output into a single element.
Explain the "Render Props" pattern.
Select the correct answer
A component takes a child component as a prop and clones it, injecting extra props before rendering it itself.
A component renders its props as plain markup automatically, so the caller never needs to define any markup.
A component takes a function prop and calls it with its internal state, letting the caller decide what to render.
A component exposes its state through context, letting any descendant read it without passing props down.
What is the difference between useEffect and useLayoutEffect, and when would using the former cause a flicker in the UI?
Select the correct answer
useEffect runs after paint, useLayoutEffect runs before it; flicker happens when the effect mutates visible layout.
useEffect runs on the server, useLayoutEffect runs on the client; flicker happens when the effect re-subscribes to a context value.
useEffect runs synchronously, useLayoutEffect runs asynchronously; flicker happens when the effect updates state on every render.
useEffect runs before paint, useLayoutEffect runs after it; flicker happens when the effect fetches data that delays the paint.
Why does React's 'Strict Mode' double-invoke effects and reducers in development, and what kind of bugs is it trying to surface?
Select the correct answer
To surface slow renders and large bundles by re-running them and exposing components that take too long to mount twice.
To surface impure render logic and missing effect cleanup by re-running them and exposing code that isn't idempotent.
To surface hydration mismatches and key errors by re-running them and exposing markup that differs from the server output.
To surface stale closures and outdated props by re-running them and exposing values that were captured in an earlier render.
What is useId used for, and why can't you just use a random number or index to generate IDs?
Select the correct answer
It generates stable unique IDs consistent across server and client renders
It produces a hashed ID derived from a component's current props and state
It creates a random ID each render to guarantee globally unique element keys
It returns an incrementing index used to track items inside a mapped list
What exactly causes a React component to re-render, and does a parent re-rendering always cause all children to re-render?
Select the correct answer
Any DOM event triggers it; parents always re-render every child without exceptions ever
State or prop changes trigger it; parents re-render children unless they're memoized
Only direct state changes trigger it; parents never force their children to re-render
Context changes alone trigger it; parents re-render children only when keys change
Explain the reconciliation process: how does React's diffing algorithm decide which parts of the DOM to update?
Select the correct answer
It re-renders the entire DOM tree from scratch whenever any single state value changes
It compares element types and keys, reusing nodes and updating only differences
It tracks every DOM node with unique IDs and queries the browser for changed elements
It compares text content of all nodes and rewrites any node whose text has changed
What is the "Virtual DOM" and how does the "Diffing Algorithm" work?
Select the correct answer
A compiled snapshot of HTML React ships to clients to skip rendering work entirely
An in-memory tree React diffs against the previous one to update the real DOM
A parallel DOM rendered off-screen that the browser swaps in after each render cycle
A browser cache of past DOM states React restores whenever a component fully unmounts
What does the 'use client' directive actually do? Does it mean the component only renders on the client?
Select the correct answer
It tells the bundler to ship the component's source to the browser and never execute it on the server at all.
It disables React hooks within the module so the component can run safely outside the server runtime entirely.
It marks a boundary so the module runs as a Client Component; it still renders on the server during SSR.
It forces the component to skip server-side rendering entirely and only hydrate after the page fully loads.
Why is it now recommended to fetch data directly inside Server Components rather than using useEffect on the client?
Select the correct answer
Fetching in Server Components caches results in localStorage, letting the client reuse them across page reloads.
Fetching on the server avoids client-side waterfalls and ships less JavaScript and data-fetching code to the browser.
Server Components automatically re-run useEffect on each request, so the data stays fresher than client fetching.
Client-side fetching is no longer supported in React 19, so Server Components are now the only way to load data.
Explain the concept of 'Actions' in React 19. How do they simplify form handling compared to the traditional useState and onSubmit pattern?
Select the correct answer
They convert every onSubmit handler into a Server Component so the form logic always runs on the server.
They replace forms with a global store that holds all input values and validates them before any submission.
They cache form input across navigations and resubmit it automatically whenever the network reconnects again.
They wrap async submissions in transitions, automatically managing pending, error, and optimistic state for you.
Why is forwardRef being deprecated in React 19, and how do we handle refs in functional components now?
Select the correct answer
Refs are now banned in function components entirely, so all ref-related logic must move into class components.
ref can now be passed as a regular prop to function components, so forwardRef is no longer needed.
ref must be accessed through the new useImperativeHandle hook, which fully replaces forwardRef.
useRef now automatically forwards itself to child components, replacing the need for any wrapper function.
What is the difference between useActionState and useFormStatus, and when would you use one over the other?
Select the correct answer
useActionState caches the action's result globally; useFormStatus subscribes any component to that cached result anywhere.
useActionState runs only on the server; useFormStatus runs only on the client to show submission progress bars.
useActionState manages an action's return value and pending state; useFormStatus reads the parent form's status from a child.
useActionState validates form fields on submit; useFormStatus resets the form once submission succeeds without errors.