React Interview Questions
Deep dive into React 18, hooks, performance optimization, and scenario-based debugging.
Why does React need a Virtual DOM?
React uses a Virtual DOM because updating the real browser DOM is slow. The Virtual DOM is a lightweight copy of the real DOM. When state changes, React updates the Virtual DOM first, compares it with the previous version (diffing), and then only updates the exact parts of the real DOM that changed.
Deep Dive
Directly manipulating the real DOM triggers expensive browser operations like layout recalculations and repaints. React minimizes this by batching updates. It creates a new Virtual DOM tree, uses a heuristic O(n) algorithm to compare it with the old tree, and generates a list of minimal operations to apply to the real DOM (Reconciliation).
Explain the useEffect dependency array and how it works.
The dependency array tells React when to re-run the effect. If you leave it empty `[]`, it runs only once on mount. If you omit it entirely, it runs on every render. If you add variables `[data]`, it runs when `data` changes.
Deep Dive
React uses `Object.is` to compare the current dependencies with the previous ones. If the references have changed, the effect runs. This is why passing objects, arrays, or functions directly as dependencies can cause infinite loops unless they are memoized with useMemo or useCallback, because their memory references change on every render.
What is Prop Drilling and how do you avoid it?
Prop drilling is when you pass data through multiple layers of components just to get it to a deeply nested child that needs it. You can avoid it by using the Context API, Redux, or Zustand.
Deep Dive
While prop drilling is fine for 1-2 levels, going deeper creates tightly coupled, hard-to-maintain code where intermediate components possess props they don't use. Aside from Context/Redux, a cleaner React pattern to avoid it is 'Component Composition'βpassing components as children.
How does React 18 Concurrent Rendering work?
Concurrent rendering allows React to interrupt a long render. Before React 18, rendering couldn't be paused. Now, React can pause a heavy background render to immediately respond to user input like typing or clicking.
Deep Dive
Concurrent features (like useTransition and useDeferredValue) mark certain state updates as 'non-urgent'. React maintains multiple versions of the UI in memory. If an urgent update (like a keystroke) comes in, React pauses the non-urgent rendering, handles the keystroke, and then resumes the background rendering.