Part 1 - Complete Interview Questions & Answer Bank
Full collection of 50 essential React interview questions, key takeaways, and self-assessment checks.
Q1: What is the Virtual DOM and how does React use it?
The Virtual DOM is a lightweight in-memory representation of the real DOM. When state changes occur, React creates a new Virtual DOM tree, compares it with the previous one using a diffing algorithm (Reconciliation), and batch updates only the changed elements in the real DOM for optimal performance.
Virtual DOM minimizes direct real DOM manipulations to boost rendering performance.
React uses a diffing algorithm during Reconciliation to compute minimal real DOM updates.
What process does React use to compare the new Virtual DOM with the previous one?
Q2: What is JSX and why do we use it in React?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like markup directly inside JavaScript files. Compilers like Babel transform JSX syntax into standard React.createElement() function calls at compile time.
JSX allows writing component structure and rendering logic in a visual, declarative syntax.
Babel transpiles JSX tags into standard
React.createElement()function calls.
What does JSX transpile to under the hood?
Q3: What is the difference between State and Props in React?
Props (short for properties) are read-only inputs passed from parent components to child components to configure them. State represents internal, dynamic data managed within a component that can change over time and triggers component re-renders when updated.
Props are immutable data passed down from parent components.
State is local component data managed dynamically that triggers re-renders on change.
Which of the following describes Props accurately?
Q4: How does the useState Hook work?
The useState hook allows functional components to manage local state. It accepts an initial state value as an argument and returns an array containing two elements: the current state value and a updater function to modify that state value.
useStatereturns an array with the current state and its setter function.Calling the state setter function schedules a re-render of the component with updated values.
What does the useState hook return?
Q5: What is the useEffect Hook and how is its dependency array used?
The useEffect hook enables functional components to perform side effects (like data fetching, subscriptions, or DOM mutations). Its behavior is controlled by a dependency array: omitting it runs every render, an empty array [] runs once on mount, and specifying dependencies [dep] runs when those values change.
useEffectencapsulates side-effect operations in functional components.The dependency array dictates when the effect executes (mount, update, or unmount cleanup).
When does a useEffect callback run if passed an empty dependency array []?
Q6: Why are keys important when rendering lists in React?
Keys are unique string identifiers used by React to track which list items have changed, been added, or been removed. Proper keys enable efficient Reconciliation during Virtual DOM diffing. Using array indices as keys is discouraged for dynamic lists as it can lead to state bugs during reordering.
Keys help React identify elements uniquely during list diffing.
Stable, unique keys prevent incorrect state mapping during list reordering or deletions.
Why is using array index as a key for dynamic lists considered bad practice?
Q7: What are the main phases of the React component lifecycle?
The React lifecycle consists of three primary phases: Mounting (component creation and insertion into DOM), Updating (re-rendering due to state or props changes), and Unmounting (removal from DOM). Functional components handle these using hooks like useEffect.
Lifecycle phases: Mounting, Updating, and Unmounting.
Class lifecycle methods (
componentDidMount,componentWillUnmount) map touseEffectin functional components.
Which lifecycle cleanup method corresponds to returning a function from useEffect?
Q8: What is the React Context API and when should you use it?
The Context API provides a way to pass data through the component tree without manually passing props at every level (prop drilling). It is ideal for global state like user authentication, theme settings, or language preferences.
Context solves prop drilling by exposing data globally to wrapped component subtrees.
Best used for broadcasted low-frequency updates like user sessions, themes, or locale.
Which hook is used to consume values from a React Context in functional components?
Q9: What is React.memo and how does it optimize performance?
React.memo is a higher-order component that memoizes functional components. It skips re-rendering a component if its incoming props have not changed according to a shallow equality check.
React.memoprevents unnecessary re-renders of functional components when props remain identical.Uses shallow comparison by default for prop diffing.
What type of comparison does React.memo perform on props by default?
Q10: What is the difference between useCallback and useMemo?
useCallback memoizes callback function instances across re-renders to maintain reference stability. useMemo memoizes the calculated result value of an expensive function call across re-renders.
useCallback(fn, deps)returns a memoized function instance.useMemo(() => value, deps)returns a memoized calculated value.
Which hook is specifically designed to memoize the computed return value of a heavy calculation?
Q11: What is the useRef hook and what are its main use cases?
useRef returns a mutable object whose .current property persists across re-renders without causing a component re-render when mutated. Common uses include storing DOM element references and holding instance values.
Mutating
ref.currentdoes NOT trigger a component re-render.Used to access underlying real DOM nodes or store persistent non-rendering values.
What happens to the component UI when the .current property of a useRef object changes?
Q12: What is the difference between Controlled and Uncontrolled components?
Controlled components have form inputs whose value is driven entirely by React state via value and onChange. Uncontrolled components maintain input state within the real DOM itself, accessing values using refs.
Controlled components rely on React state as the single source of truth for input values.
Uncontrolled components store value state in the DOM and read values using refs.
Which element property dictates a input as a Controlled Component in React?
Q13: What is React.Fragment and why is it useful?
React.Fragment (or <>...</>) allows grouping a list of children elements without adding extra wrapper nodes (like <div>) to the real DOM, keeping DOM layout trees clean.
Groups child elements without adding unnecessary DOM wrapper nodes.
Can accept
keyprops when using full<React.Fragment key={id}>syntax.
What is the primary benefit of using React.Fragment over a standard div wrapper?
Q14: What is a Higher-Order Component (HOC) in React?
A Higher-Order Component (HOC) is a pure function that takes a component as an argument and returns a new enhanced component. HOCs are used for reusing component logic across an application (e.g., withRouter, connect).
HOCs are design patterns for reusing component logic by wrapping components.
Follows functional composition:
const EnhancedComponent = hoc(WrappedComponent).
What does a Higher-Order Component accept and return?
Q15: What are Custom Hooks and why would you write one?
Custom Hooks are JavaScript functions whose names start with use and can call other React hooks. They allow extracting reusable stateful logic out of components into isolated functions for sharing across the application.
Custom hooks encapsulate reusable stateful behavior across components.
Must follow Hook naming rules (
usePrefix) to allow static linting.
What naming convention MUST Custom Hooks follow in React?
Q16: What are the two core Rules of Hooks in React?
- Call hooks only at the top level of components/custom hooks (never inside loops, conditions, or nested functions). 2. Call hooks only from React function components or custom hooks.
Never call hooks conditionally or inside loops to guarantee hook invocation order.
Only call hooks from React function components or custom hooks.
Why must hooks only be called at the top level of a function component?
Q17: What are Error Boundaries in React?
Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire component tree.
Error boundaries catch rendering errors in child component subtrees.
Must be implemented using class components with
componentDidCatchorgetDerivedStateFromError.
Which lifecycle method makes a class component an Error Boundary?
Q18: How do React.lazy and Suspense enable code splitting?
React.lazy() allows dynamic imports of components as separate bundle chunks. <Suspense> wraps lazy components, rendering a fallback UI (like a loading spinner) while the JavaScript chunk is fetched.
React.lazy()defers loading component code until it is rendered.<Suspense fallback={<Spinner />}>displays placeholder UI while lazy chunks load.
Which component is required to wrap a React.lazy component to display a fallback loader?
Q19: What is Prop Drilling and how can it be avoided?
Prop Drilling occurs when props are passed through multiple intermediate components that do not need them, simply to reach a deeply nested child. It can be avoided using React Context, component composition, or state management tools.
Prop drilling creates unnecessary component coupling down deep hierarchies.
Avoid via React Context, Redux/Zustand, or component composition techniques.
Which design pattern helps avoid prop drilling without using external state libraries?
Q20: What are Synthetic Events in React?
SyntheticEvent is React's cross-browser wrapper around the native browser DOM event. It provides a consistent interface across different browser implementations while delegating events at the root container for efficiency.
Normalizes event properties across all web browser environments.
Uses event delegation attached to the root root container element.
Where does React attach event listeners to handle user events efficiently?
Q21: When should you use useReducer instead of useState?
useReducer is preferred over useState for complex state logic involving multiple sub-values, when next state depends on previous state, or when managing state transitions using Redux-style action dispatches.
useReducermanages complex or grouped state state machines via(state, action) => newState.Improves maintainability by decoupling state updates from event handlers.
What is the signature of the reducer function passed to useReducer?
Q22: What does React.StrictMode do in development?
React.StrictMode is a development tool for highlighting potential problems. It intentionally double-invokes render functions, state setters, and effect cleanup functions to help detect unintended side effects and deprecations.
StrictModechecks for unsafe lifecycles, deprecated APIs, and unexpected side-effects.Double-invokes functions in development mode only (disabled in production builds).
Why does React.StrictMode intentionally render components twice in development mode?
Q23: What are React Portals and when are they used?
Portals (ReactDOM.createPortal) provide a way to render children elements into a DOM node that exists outside the DOM hierarchy of the parent component, useful for modals, tooltips, and overlays.
Renders React elements into external DOM containers.
Preserves React event bubbling through the virtual React tree regardless of DOM parentage.
Which method creates a React Portal?
Q24: How does React diffing algorithm achieve O(n) complexity?
React reduces standard $O(n^3)$ tree diffing to $O(n)$ by applying two heuristics: two elements of different types generate different trees, and lists of child elements are tracked using developer-provided key props.
Heuristic assumptions optimize diffing from cubic $O(n^3)$ to linear $O(n)$ time complexity.
Changing element types unmounts the old subtree completely and builds a new one.
What happens in React diffing when an element changes its tag type from <div> to <section>?
Q25: What is React Fiber and what problem did it solve?
React Fiber is the re-implemented core algorithm introduced in React 16. It enables incremental rendering by splitting rendering work into chunk units (fibers) that can be paused, prioritized, aborted, or resumed.
Fiber allows pausing and prioritizing rendering work to avoid blocking main browser threads.
Enables smooth UI responsiveness and concurrent rendering features.
What primary feature did React Fiber introduce over the old stack reconciler?
Q26: What is Automatic Batching in React 18?
Automatic batching groups multiple state updates together into a single re-render for better performance. React 18 automatically batches updates inside event handlers, promises, setTimeout, and native event handlers.
Groups multiple state updates into single re-renders to eliminate extra renders.
React 18 extends automatic batching everywhere (promises, timers, native handlers).
How can you opt out of automatic batching in React 18 if immediate render is needed?
Q27: What is the difference between useEffect and useLayoutEffect?
useEffect runs asynchronously after browser paint. useLayoutEffect runs synchronously after all DOM mutations but before the browser paints screen updates, ideal for measuring DOM dimensions.
useEffectis non-blocking and executes after browser layout and paint.useLayoutEffectfires synchronously before paint, preventing visual layout flickering.
When should you prefer useLayoutEffect over useEffect?
Q28: What is React.forwardRef and when is it necessary?
React.forwardRef allows parent components to pass a ref through an intermediate child component down to an underlying real DOM element or child component node.
Forwards refs down component hierarchies to expose underlying DOM nodes.
Essential for reusable design system components requiring DOM focus/measurement.
What parameters does a component wrapped in React.forwardRef receive?
Q29: How do you extract form values using refs in uncontrolled forms?
Attach a ref object to each input tag via <input ref={inputRef} />. Read values on submit using inputRef.current.value without updating React state on every keystroke.
Eliminates per-keystroke re-renders by skipping state bindings.
Access form values on demand via
ref.current.valueduring submission.
How do you access an input value in an uncontrolled component using useRef?
Q30: What is the useId hook introduced in React 18?
useId is a hook for generating unique ID strings that are stable across server-side and client-side rendering, preventing hydration mismatch warnings for accessibility attributes (htmlFor, aria-describedby).
Generates unique, deterministic IDs for accessibility attributes.
Guarantees matching ID strings between SSR and client hydration.
What primary problem does the useId hook solve?