Search IOCombats

Search challenges, guides, questions and articles

React Interview Questions

90 curated react interview questions with detailed answers and examples.

← Browse all interview questions

Use useRef to create a mutable reference that React attaches to a DOM node after mount. Access the node via ref.current inside useEffect, not during render. Use callback refs to measure elements and forwardRef to expose a child component's DOM node to a parent.

intermediateadvanced hooks-and-patternsreactuseRefdom manipulation

useEffect with an empty dependency array replaces componentDidMount. With a dependency array it replaces componentDidUpdate for specific values. With a cleanup return it replaces componentWillUnmount. React.memo replaces shouldComponentUpdate. useLayoutEffect replaces getSnapshotBeforeUpdate.

intermediateadvanced hooks-and-patternsreactuseEffectlifecycle

A controlled component has its value driven by React state. An uncontrolled component lets the DOM own the value, read via a ref on submit. Controlled enables real-time validation and formatting. Uncontrolled is mandatory for file inputs and is used by React Hook Form for performance.

intermediateadvanced hooks-and-patternsreactformscontrolled components

Custom hooks extract stateful logic into reusable functions. The use prefix enforces Rules of Hooks via the linter. Return a named object, not a tuple, for non-breaking extensibility. Add AbortController cleanup to prevent race conditions when the URL dependency changes.

advancedadvanced hooks-and-patternsreactcustom hookreuse logic

A HOC is a function that takes a component and returns an enhanced version with added behavior. Every HOC must spread {...props} to avoid swallowing parent props, set displayName for readable DevTools output, and use React.forwardRef for ref forwarding. HOCs are largely superseded by custom hooks but remain correct when you need to intercept rendering.

intermediateadvanced hooks-and-patternsreacthochigher order components

React Portals render a component into a DOM node outside the React root. This lets modals, tooltips, and dropdowns escape overflow:hidden and z-index constraints in the parent tree while remaining in the React component tree for event bubbling and context access.

advancedadvanced hooks-and-patternsreactportalmodal

Render props invert rendering control by passing state through a function call. HOCs operate at the component definition level and inject behavior via wrapped props. Both are superseded by custom hooks for logic sharing, but remain the right choice in specific scenarios.

advancedadvanced hooks-and-patternsreactrender propshoc

Pass callback functions from parent to child as props to enable child-to-parent communication in React.

beginnercomponent communicationreactcallback propscomponent communication

Understand what the Context API provides, what Redux adds on top of it, and how to decide which to reach for in a given situation.

intermediatecomponent communicationreactcontext apiredux

Build a typed context with createContext, a Provider that holds state, and a custom hook for safe consumption.

intermediatecomponent communicationreactcontext apistate management

Set fallback values for optional props using destructuring defaults in functional components and understand when to use defaultProps.

beginnercomponent communicationreactpropsdefault props

Use a controlled radio group with useState to capture the selected value and reflect it in another element.

beginnercomponent communicationreactradio buttoncontrolled component

Use controlled inputs with useState to mirror user-typed text into another element in real time.

beginnercomponent communicationreactcontrolled componentuseState

Use forwardRef with useImperativeHandle to expose imperative methods from a child component, or use controlled props to manage disabled state from the parent.

intermediatecomponent communicationreactuseRefforwardRef

Understand React synthetic events, event delegation, common patterns for handlers, and how to prevent default behavior and stop propagation.

beginnercomponent communicationreactsynthetic eventsevent handling

Pass any JavaScript value from parent to child as props, understand how props flow in React, and know what children can and cannot do with them.

beginnercomponent communicationreactpropsparent-child communication

Understand why prop drilling is a maintainability problem and know the four solutions: component composition, Context, state managers, and custom hooks.

intermediatecomponent communicationreactprop drillingcontext api

Apply conditional CSS in React using className with ternary, the cn() utility, and inline styles. Know which approach to use and when.

beginnerconditional renderingreactconditional stylesclassName

Render elements conditionally in React using if/else, ternary operators, logical AND, and null returns. Know the gotchas for each approach.

beginnerconditional renderingreactconditional renderingternary

Conditional rendering in React is JavaScript control flow applied to JSX. Learn the four patterns, when to use each, and the gotchas that catch candidates off guard.

beginnerconditional renderingreactconditional renderingjsx

Use dangerouslySetInnerHTML to render HTML strings from a CMS or API, and always sanitize external content with DOMPurify to prevent XSS.

beginnerconditional renderingreactdangerouslySetInnerHTMLXSS

The key prop lets React match list elements across renders for efficient diffing. Using index as key is a common bug. Understand why and how to fix it.

beginnerconditional renderingreactkey proplist rendering

Use map() to transform arrays into JSX elements. Know when to use filter() and flatMap(), and how to handle nested arrays and empty states.

beginnerconditional renderingreactmaplist rendering

Objects cannot be mapped directly in JSX. Use Object.entries(), Object.keys(), or Object.values() to convert to arrays first, then map to JSX.

intermediateconditional renderingreactobjectObject.entries

Toggle element visibility in React by combining useState with conditional rendering or CSS. Know when to unmount vs keep mounted.

beginnerconditional renderingreactconditional renderinguseState

Fetch data inside useEffect with async/await, handle loading and error states, and avoid the stale closure and race condition bugs that affect real production code.

intermediatedata fetchingreactuseEffectfetch

Error boundaries are class components that catch render errors in their subtree and show a fallback. Understand getDerivedStateFromError, componentDidCatch, and when to use react-error-boundary instead.

advancederror handlingreacterror boundaryclass component

Error boundaries are React components that catch render errors in their subtree and show fallback UI. Understand what they catch, what they miss, and how they relate to a production error strategy.

advancederror handlingreacterror boundariescomponentDidCatch

Understand the anatomy of a React function component, how JSX compiles, and the rules that make a valid component.

beginnerfundamentalsreactcomponentsjsx

Understand the key differences between functional and class components, why hooks changed everything, and why functional components are now the standard.

beginnerfundamentalsreactfunctional componentsclass components

Understand the difference between props and state in React, when to use each, and how they interact to drive rendering.

beginnerstate lifecyclereactpropsstate

Understand the heuristics React uses to compare virtual DOM trees efficiently and how keys enable correct list reconciliation.

intermediatefundamentalsreactdiffingreconciliation

Understand how React reconciles the virtual DOM with the real DOM, what triggers re-renders, and how the fiber architecture enables concurrent rendering.

intermediatefundamentalsreactreconciliationvirtual dom

Understand what JSX compiles to, why it exists, and the rules that govern how you write it correctly.

beginnerfundamentalsreactjsxbabel

Understand React as a UI library, how its declarative model and virtual DOM work, and why it became the dominant choice for frontend development.

beginnerfundamentalsreactvirtual domdeclarative

Understand what the virtual DOM is, how it enables efficient updates, and what its real performance tradeoffs are.

beginnerfundamentalsreactvirtual domperformance

Render a controlled select dropdown from an array of strings or objects using map(). Know how to track the selected value and handle the placeholder option.

beginnerforms and-inputsreactselectdropdown

Controlled components let React own the input value through state. Uncontrolled components let the DOM own the value and read it via refs. Know when each is appropriate.

intermediateforms and-inputsreactcontrolled componentsuncontrolled components

useReducer separates state transition logic from the component using a reducer function and typed actions. Understand when it is the right tool over useState.

intermediateforms and-inputsreactuseReducerstate management

Build the same counter component with both useState and useReducer. Understand the tradeoffs and know when to reach for each.

intermediateforms and-inputsreactuseStateuseReducer

Build chained dropdowns where the second options list derives from the first selection. Extend the pattern to API-driven options and three-level chains.

intermediateforms and-inputsreactdependent dropdownscontrolled select

Track a select value in state and display it anywhere on the page. This is the controlled component pattern applied to dropdowns and is the foundation for summary panels and confirmation UIs.

beginnerforms and-inputsreactcontrolled selectuseState

Render a controlled radio group from an array using map(). Understand the name attribute for grouping, checked from state, and accessibility with fieldset and legend.

beginnerforms and-inputsreactradio buttoncontrolled input

React forms work through controlled inputs where state is the single source of truth. Understand the cycle, real-time validation, input formatting, and the multi-field pattern with a shared handler.

intermediateforms and-inputsreactformscontrolled inputs

Filter a list in real time by combining a controlled input with array filter(). Add debouncing for API search and useMemo for expensive client-side filtering.

intermediateforms and-inputsreactsearchfilter

Implement a character counter for a textarea using a controlled input. Understand why the counter should be derived state, not stored state, and when useRef is the right tool instead.

intermediateforms and-inputsreacttextareacharacter counter

Debouncing delays execution until a user pauses. Build a useDebounce hook with setTimeout and clearTimeout cleanup in useEffect. Use it for search inputs that fetch from an API. Do not debounce client-side filtering — use derived state instead.

intermediateperformance optimizationreactdebounceperformance

React.lazy wraps a dynamic import() so the component code is fetched only when first rendered, not included in the initial bundle. Suspense shows a fallback during the load. Always pair with an ErrorBoundary to handle chunk load failures. React.lazy requires default exports.

intermediateperformance optimizationreactlazy loadingperformance

PropTypes validate prop types and required props at runtime in development, logging console warnings on violations. In TypeScript projects, PropTypes are superseded by interface declarations and compile-time checking. Know what each serves: PropTypes = runtime dev warnings, TypeScript = compile-time safety.

intermediateperformance optimizationreactprop-typesvalidation

A pure component skips re-rendering when its props and state are shallowly equal to the previous render. PureComponent is the class equivalent; React.memo is the function component equivalent. Both perform shallow equality checks — object and function prop references must be stable or the optimization is bypassed.

intermediateperformance optimizationreactpure componentreact memo

React Fiber replaces the synchronous call-stack reconciler with interruptible work units. Concurrent Mode (via createRoot) exposes this as priority scheduling: startTransition marks updates as non-urgent so React can pause and prioritize user input. startTransition does not move work off the main thread.

advancedperformance optimizationreactreact fiberconcurrent mode

React.lazy wraps a dynamic import() to split a component into its own chunk. Suspense catches the pending state and renders a fallback. Pair with an ErrorBoundary for chunk load failures. React.lazy requires default exports — adapt named exports with a .then() wrapper.

advancedperformance optimizationreactreact lazysuspense

React.memo skips re-rendering a component when props are shallowly equal to the previous render. Inline objects and function props silently defeat it — pair with useMemo and useCallback on the parent side. Profile first; memo adds comparison overhead and should be applied surgically.

intermediateperformance optimizationreactreact memoperformance

React re-renders a component when its state changes, its props change, or its parent re-renders. The third trigger cascades through entire subtrees by default. Reconciliation limits DOM mutations. Memoization prevents component function calls. Profile before optimizing.

advancedperformance optimizationreactrenderingoptimization

useCallback memoizes a function reference so child components wrapped in React.memo skip re-rendering when the parent re-renders. Without React.memo on the child, useCallback adds overhead with no benefit. The dependency array must include every value the callback closes over.

advancedperformance optimizationreactuseCallbackoptimization

useMemo caches the return value of a factory function and recomputes only when listed dependencies change. It prevents unrelated state changes from re-triggering expensive computations. It does not make a slow computation fast — when the dependency that drives the expense changes, the work runs regardless.

intermediateperformance optimizationreactuseMemoperformance

useMemo caches a computed value; useCallback caches a function reference. useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). useCallback without React.memo on the child adds overhead with no benefit. Both require an accurate dependency array to avoid stale closures.

intermediateperformance optimizationreactuseMemouseCallback

Server-side rendering sends pre-built HTML for fast first paint and SEO. Client-side rendering builds the UI in the browser after downloading JavaScript. Understand hydration, the four rendering modes, and when each applies.

advancedrendering strategiesreactssrcsr

A ProtectedRoute component checks session state before rendering children and redirects unauthenticated users to login. Handle the isLoading state to prevent flash redirects, preserve the originally-attempted URL, and extend to role-based access.

advancedroutingreactreact routerauthentication

React Router intercepts browser navigation via the History API, renders the matching component, and updates the URL without a server round-trip. Understand BrowserRouter, Routes, nested routes with Outlet, useParams, useNavigate, and the server config requirement for direct URL access.

intermediateroutingreactreact routerspa

Correctly add items to an array in React state using spread, concat, or functional updates without mutating the original array.

beginnerstate lifecyclereactuseStatearrays

Use useEffect to run logic after state updates, and useLayoutEffect when you need to act before the browser paints.

intermediatestate lifecyclereactuseEffectuseLayoutEffect

Use useEffect with an empty dependency array to run logic once after the first render, equivalent to componentDidMount.

beginnerstate lifecyclereactuseEffectlifecycle

Use useEffect without a dependency array to run logic after every render, and understand when this pattern is appropriate versus problematic.

intermediatestate lifecyclereactuseEffectlifecycle

Use useReducer, a counter state, or the key prop to force a component to re-render or fully reset without relying on useState directly.

intermediatestate lifecyclereactrerenderuseReducer

Understand what hooks are, the rules that govern them, and how useState and useEffect replace class component state and lifecycle methods.

beginnerstate lifecyclereacthooksuseState

Understand what triggers React re-renders, how to use state and props correctly, and how to prevent unnecessary re-renders.

beginnerstate lifecyclereactrerenderstate

Jest runs tests and provides assertions. React Testing Library (RTL) queries the DOM the way users interact with it — by role, label, and text. Test behavior, not implementation. Use userEvent over fireEvent for realistic simulation.

advancedtestingreactjestreact testing library

Track currentPage in state, derive the visible data slice and total pages, disable navigation at boundaries, and reset to page 1 when the data source changes. Know when to paginate client-side versus server-side.

intermediateui componentsreactpaginationui components

React auto-escapes output to prevent XSS, but dangerouslySetInnerHTML, eval, and third-party content require explicit sanitization. Use HttpOnly cookies for JWTs, validate input on both sides, add CSP headers, and audit dependencies regularly.

advancedui componentsreactsecurityxss

Design a full-featured calendar with day/week/month views, event creation, drag-to-resize, recurring events, and conflict detection.

advancedui patternsreactcalendarscheduler

Build a performant, swipe-friendly carousel with auto-play, infinite looping, touch/keyboard navigation, and animated transitions.

intermediateui patternsreactcarouselslider

Design a real-time collaborative whiteboard using canvas, WebSockets/WebRTC, CRDT syncing, undo/redo, and multi-user presence.

advancedui patternsreactwhiteboardcanvas

Design a performant, accessible data table with client-side sorting, column filtering, search, pagination, and memoization.

advancedui patternsreactdata tablesorting

Design a Kanban board with drag-and-drop between columns, persistence, optimistic UI updates, and accessibility considerations.

advancedui patternsreactdrag and dropkanban

Learn to build a dynamic form builder in React that renders form fields based on JSON schema, supports validation, conditional logic, and reusable components.

advancedui patternsreactform builderjson schema

Build a resilient file upload component with progress, cancel, retry, chunking notes, and UX considerations for large files.

advancedui patternsreactfile uploadprogress

Design and implement a production-ready infinite scroll in React — covers IntersectionObserver, performance, virtualization, and UX tradeoffs.

advancedui patternsreactinfinite scrollintersectionobserver

Create a global modal manager with stacking, portal rendering, focus trapping, ESC handling, and dynamic modal types.

advancedui patternsreactmodalportal

Build a reusable multi-step wizard in React with controlled state, validation per step, progress indicators, and persistence.

advancedui patternsreactwizardmulti step

Build a multi-tab (wizard-like) form that persists data across tabs, auto-saves to localStorage or backend, handles validation per tab, and recovers on reload.

intermediateui patternsreactformspersistence

Design a performant multi-select with search, keyboard navigation, tag rendering, virtualization for large option sets, and async loading.

advancedui patternsreactmultiselectdropdown

Build a global toast/notification system with portal rendering, queueing, auto-dismiss, animations, and accessibility.

intermediateui patternsreacttoastnotifications

Design a real-time poll system using WebSockets or SSE, optimistic voting, conflict handling, caching, and animations for live result updates.

advancedui patternsreactpollingwebsocket

Build a scalable real-time chat UI using WebSockets, presence indicators, message queues, retries, and optimistic rendering.

advancedui patternsreactchatwebsocket

Design a minimal Medium-style rich text editor with contentEditable, commands, history, block/inline formats, selection APIs, and plugins.

advancedui patternsreactrich text editorcontentEditable

Implement a fully working autocomplete component with debouncing, keyboard navigation, async suggestions, loading states, and accessibility.

advancedui patternsreactautocompletesearch

Design a shopping cart that updates the UI instantly (optimistic), persists to backend, and rolls back on failure. Covers conflict handling and idempotency.

advancedui patternsreactoptimistic updatesshopping cart

Build a flexible star rating component supporting half-stars, hover preview, keyboard accessibility, and controlled/uncontrolled usage.

intermediateui patternsreactratingui component

Design a high-performance virtualized list capable of rendering 100k+ rows with minimal DOM nodes, supporting variable heights, infinite scroll, and windowing strategies.

advancedui patternsreactvirtualizationperformance