React Interview Questions — Medium
Real-world mechanisms, state management, edge cases, performance trade-offs, and practical coding.
Q1Explain the React Context API. When should you use it, and how do you prevent unnecessary re-renders in consumers?
Answer: The Context API is React's built-in system for passing data down the component tree without manually threading props through intermediate layers (avoiding "prop drilling").
How it works:
React.createContext(defaultValue): Creates a Context object.Provider: A component that wraps the component subtree and accepts avalueprop.useContext(Context): A hook that lets components subscribe to context changes.
When to use it: Use Context for global, low-frequency updates, such as user authentication state, UI themes (light/dark mode), active locales/languages, or shared multi-step wizard state.
The Performance Problem (Unnecessary Re-renders):
Whenever the value of a Context Provider changes, all descendant components that consume that Context will re-render, even if they only use a subset of the context value that didn't change. Furthermore, if the Provider passes an object literal (e.g., value={{ state, dispatch }}), a new object reference is created on every render, triggering updates for all consumers.
How to optimize and prevent these re-renders:
- Memoize the Value Object: Wrap the value passed to the Provider in
useMemoso its reference remains stable unless the state changes.const contextValue = useMemo(() => ({ state, dispatch }), [state]); return <MyContext.Provider value={contextValue}>{children}</MyContext.Provider>; - Split Contexts: Separate state and dispatch into two different Contexts. This ensures that components that only dispatch actions (which never change) don't re-render when the state updates.
- Use Component Splitting / Memoization: Wrap the direct consumer component in
React.memo, or use child components passed aschildren(which React won't re-render unless their parent changes props).
Q2What are `useMemo` and `useCallback`? How do they work, and what is their performance overhead?
Answer:
useMemo and useCallback are optimization hooks designed to prevent expensive recalculations and unnecessary child component re-renders by caching values and function references.
useMemo(fn, deps):- Purpose: Memoizes the result of an expensive calculation.
- How it works: Executes the function and caches the result. On subsequent renders, it returns the cached value unless the dependencies in the array change.
useCallback(fn, deps):- Purpose: Memoizes the function reference itself.
- How it works: Returns the exact same function reference between renders unless its dependencies change. This is crucial when passing callback functions as props to memoized child components (
React.memo) to avoid breaking prop-equality checks. - Note:
useCallback(fn, deps)is syntactically equivalent touseMemo(() => fn, deps).
Performance Overhead & Overuse:
Developers often fall into the trap of wrapping every function in useCallback and every computation in useMemo. This can actually hurt performance due to:
- Memory Overhead: Storing dependency arrays and closures in memory.
- CPU Overhead: Running a dependency comparison check (
Object.is) on every single render.
When to use them:
- Use
useMemowhen performing complex computations (e.g., filtering or sorting arrays with thousands of items). - Use
useCallbackwhen passing a callback to a child component optimized withReact.memo, or when the function itself is a dependency in another hook (e.g., inside auseEffect).
Q3Explain the heuristics of React's Virtual DOM reconciliation (diffing) algorithm.
Answer: The Virtual DOM diffing process determines how to update the real DOM when state changes. A generic tree comparison algorithm has a time complexity of $O(n^3)$. To achieve real-time performance, React uses a heuristic O(n) algorithm based on two main assumptions:
- Two elements of different types will produce different trees.
If React detects that a parent node has changed type (e.g., changing from
<div>to<span>, or from a<Counter>component to a<Profile>component), it doesn't try to diff them. Instead, it tears down the entire subtree, destroys its state, and mounts a brand new tree from scratch. - The developer can hint at which child elements are stable across renders with a
keyprop. When comparing children of the same parent, React matches keys to map nodes from the old tree to the new tree. This allows it to efficiently detect when items are inserted, deleted, or reordered without rebuilding the entire list.
Reconciliation details for same-type elements: If two React elements are of the same type, React keeps the DOM node, updates only the changed attributes or CSS classes, and then recursively diffs their children.
Q4What are Custom Hooks, what rules do they follow, and how do they share logic?
Answer:
A Custom Hook is a JavaScript function whose name starts with use and can call other React hooks. They are the primary mechanism in React for reusing stateful logic across multiple components.
Key characteristics:
- No Shared State: Custom hooks do not share state. Every time a component calls a custom hook, all state variables and effects inside that hook are initialized completely independently. They share behavior and logic, not data.
- Abstracting Complexity: They allow clean encapsulation of operations like fetching data, subscribing to window resizing, handling form inputs, or listening to keyboard events.
The Rules of Hooks (which custom hooks must also follow):
- Only Call Hooks at the Top Level: Do not call hooks inside loops, conditions, or nested functions. This ensures React can maintain the correct hook call order across renders (internally, React relies on the exact array index of hook execution to match state variables to their hook calls).
- Only Call Hooks from React Functions: Call them from React functional components or other custom hooks. Do not call them from plain JavaScript helper functions.
Q5What is React Portals, and what are their common use cases?
Answer: React Portals provide a way to render a component's virtual DOM tree into a physical DOM node that exists outside the parent component's DOM hierarchy.
ReactDOM.createPortal(child, containerNode)
Common Use Cases:
- Modals, tooltips, dialogs, and toast notifications. These elements often need to visual break out of their parent containers that might have styling like
overflow: hidden,position: relative, or customz-indexstacking contexts.
Portals & Event Bubbling: Crucially, even though a portal component renders somewhere else in the physical DOM, it still behaves like a normal React child component in terms of React's event system. This means that:
- Events (like mouse clicks) fired inside a portal will still bubble up to the virtual React parent components, regardless of where they are in the physical HTML DOM. This allows parent components to capture events from portals seamlessly.
Unlock the remaining 48 React (Medium) questions
You've completed the 5 free sample questions. Get unrestricted lifetime access to every question, model answer, implementation challenge, and all 27+ technologies for a single payment.
₹399 India / $9 International · One-time settlement · Zero subscription