Prepare for your next React.js interview with our comprehensive collection of React interview questions and answers, curated for beginners to senior-level developers. This page covers all critical topics including JSX, components, props, state management, hooks, advanced patterns, Redux, routing, testing, performance optimization, and modern React concepts. Each question comes with a detailed explanation, practical code examples, and insights into why interviewers ask it, helping you master React.js fundamentals and advanced patterns to confidently tackle technical interviews.
Styling in React components can be applied using external CSS files, inline styles defined as JavaScript objects, CSS Modules, or CSS-in-JS libraries. At a fundamental level, React supports traditional CSS via className and inline styles via the style prop, allowing developers to choose between static and dynamic styling approaches.
Why does React use className instead of class for CSS classes?
React uses className instead of class because class is a reserved keyword in JavaScript. JSX maps className to the standard HTML class attribute at runtime while avoiding conflicts with JavaScript syntax.
<div className="card">Card Content</div>
Why Interviewers Ask This
This checks foundational JSX knowledge and understanding of how JSX integrates JavaScript and HTML.
Common Mistakes
Using class instead of className and relying on browser behavior to fix it.
Inline styles in React are written as JavaScript objects rather than strings. CSS property names use camelCase instead of kebab-case, and values are usually strings or numbers. This allows styles to be computed dynamically using JavaScript logic.
Conditional styling in React is typically achieved by dynamically changing class names or inline style values based on component state or props. This allows the UI to react visually to user interaction, application state, or business logic.
What are the advantages and disadvantages of inline styles in React?
Inline styles provide dynamic styling capabilities and avoid CSS naming conflicts, but they lack support for pseudo-classes, media queries, and can reduce separation of concerns. They are best used for dynamic values rather than large style definitions.
Why Interviewers Ask This
Interviewers want to see trade-off analysis rather than tool memorization.
Common Mistakes
Using inline styles for complex layouts or hover effects.
How does React handle CSS specificity and conflicts?
React does not alter CSS specificity rules. Styles applied via className follow standard CSS cascading and specificity rules, while inline styles have higher priority than external styles. Understanding this is critical to predicting how styles are applied in complex applications.
Why Interviewers Ask This
This reveals whether candidates understand that React does not abstract CSS behavior.
Why is inline styling sometimes discouraged in large React applications?
In large applications, excessive inline styling can lead to poor maintainability, duplicated style logic, and reduced readability. It also prevents the use of advanced CSS features such as media queries and pseudo-selectors, making responsive design harder to manage.
Why Interviewers Ask This
Interviewers ask this to assess architectural thinking and scalability concerns.
Common Mistakes
Believing inline styles are inherently bad rather than context-dependent.
Dynamic styling can trigger frequent re-renders if styles are recalculated on every render. When not memoized or optimized, this can lead to unnecessary updates. Using stable class names and memoization techniques helps mitigate performance issues.
How does React compare inline styles with traditional CSS during reconciliation?
Inline styles are treated as part of the element’s props. During reconciliation, React performs a shallow comparison of style objects and updates only the properties that change. Stable references help React minimize DOM mutations.
Why Interviewers Ask This
This question targets understanding of reconciliation and rendering optimization.
Common Mistakes
Assuming inline styles always cause full re-renders.
When should CSS files be preferred over inline styles in React?
CSS files should be preferred when styles are static, reused across components, or require advanced features like media queries, animations, or pseudo-classes. Inline styles are best reserved for dynamic values driven by state or props.
Why Interviewers Ask This
Interviewers want practical decision-making, not absolute rules.
Common Mistakes
Overusing inline styles due to convenience rather than design considerations.
A functional component is a JavaScript function that returns JSX and represents a reusable UI unit. It receives props as arguments and must be a pure function, meaning it returns the same UI for the same input.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Why Interviewers Ask This
This question checks whether the candidate understands the modern and preferred way of building components in React.
Common Mistakes
Confusing functional components with regular functions
What does it mean that functional components should be pure?
A pure functional component does not modify external variables or cause side effects during rendering. For the same props and state, it always returns the same JSX.
Why Interviewers Ask This
This tests conceptual understanding of React’s rendering philosophy and predictability.
What are Hooks and why are they used with functional components?
Hooks are functions that allow functional components to use React features such as state, lifecycle behavior, and context without using class components.
How do functional components differ from class components internally?
Function components rely on hooks and closures, while class components rely on instances and lifecycle methods. Function components are simpler and easier to optimize.
Why Interviewers Ask This
Interviewers use this to separate surface-level React users from those who understand architectural differences.
Common Mistakes
Thinking functional components are slower
Believing lifecycle methods still exist in functional components
How does React handle re-rendering of functional components?
Function components re-render whenever their props or state change. React compares the previous and next virtual DOM trees and updates only the necessary parts of the real DOM.
Why Interviewers Ask This
This question evaluates understanding of React’s rendering and reconciliation behavior.
JSX (JavaScript XML) is a syntax extension for JavaScript that allows writing HTML-like structures inside JavaScript. JSX is not HTML; it is transpiled into React.createElement() calls during build time, making UI code more readable and declarative.
Why Interviewers Ask This
Interviewers use this question to verify whether the candidate understands that JSX is a syntax abstraction and not actual HTML. It tests conceptual clarity around how React elements are created and rendered.
No, JSX is not mandatory. React can be written using React.createElement() directly. JSX is recommended because it improves readability and developer experience.
Why Interviewers Ask This
This question evaluates whether the candidate understands that JSX is optional and syntactic sugar. It also reveals familiarity with React’s core API.
JSX must return a single root element because React.createElement() returns only one element. Multiple elements must be wrapped in a container or React.Fragment.
<>
<Header />
<Footer />
</>
Why Interviewers Ask This
This tests understanding of how JSX maps to React element trees and why fragments exist.
Common Mistakes
Wrapping everything in unnecessary divs
Not knowing about React.Fragment or shorthand syntax
What is dangerouslySetInnerHTML and why is it dangerous?
dangerouslySetInnerHTML allows inserting raw HTML into the DOM. It bypasses React’s built-in escaping and can expose the app to XSS vulnerabilities if misused.
JSX is converted into JavaScript objects representing React elements, not actual DOM nodes. React reconciles these objects and updates the real DOM efficiently.
Why Interviewers Ask This
Interviewers ask this to differentiate between surface-level React users and those who understand React’s rendering internals.
What is list rendering in React and why is it commonly used?
List rendering in React refers to the process of displaying multiple similar UI elements by iterating over an array of data. It is commonly used when rendering collections such as menus, tables, cards, or dynamic datasets fetched from APIs. React leverages JavaScript array methods like map() to transform data into UI elements in a declarative and readable way.
{items.map(item => <li>{item}</li>)}
Why Interviewers Ask This
Interviewers ask this to confirm that the candidate understands how React handles dynamic UI generation from data rather than hard-coded markup.
Common Mistakes
Using loops like for or while inside JSX instead of array methods, or attempting to manually repeat JSX elements.
Why does React require a key prop when rendering lists?
React requires a key prop to uniquely identify each element in a list. Keys help React efficiently determine which items have changed, been added, or removed during reconciliation. This allows React to update only the necessary DOM elements instead of re-rendering the entire list.
<li key={item.id}>{item.name}</li>
Why Interviewers Ask This
This question tests understanding of React’s reconciliation algorithm and performance optimization strategies.
Common Mistakes
Ignoring the key warning or assuming keys are only required to remove console errors.
What happens if you do not provide keys in a list?
If keys are not provided, React falls back to using array indexes internally, which can lead to inefficient updates and UI inconsistencies when items are reordered, added, or removed. React will also display a warning in the console to indicate improper list rendering.
Why Interviewers Ask This
Interviewers want to evaluate awareness of subtle UI bugs caused by improper reconciliation.
Common Mistakes
Assuming the UI will always behave correctly without keys.
Why is using array index as a key considered an anti-pattern?
Using array index as a key can cause incorrect UI updates when list items change order, are inserted, or removed. Since indexes change based on position rather than identity, React may reuse components incorrectly, leading to bugs such as incorrect state association or unexpected re-renders.
A good key is a stable, predictable, and unique identifier that does not change between renders. Typically, this comes from a database ID or a unique value intrinsic to the data. Stable keys ensure React can correctly track element identity across updates.
<Item key={user.id} user={user} />
Why Interviewers Ask This
Interviewers look for best practices rather than workarounds.
During reconciliation, React compares the previous and next virtual DOM trees. Keys allow React to match elements between renders, identify moved or removed items, and minimize DOM mutations. Without proper keys, React may destroy and recreate elements unnecessarily.
Why Interviewers Ask This
Tests understanding of React internals and performance behavior.
Keys must be unique only among siblings within the same list. The same key values can safely be reused in different lists or different component trees without causing conflicts.
Why Interviewers Ask This
Checks scoping knowledge of keys.
Common Mistakes
Assuming keys must be globally unique across the entire application.
When keys are incorrect or unstable, React may reuse component instances improperly. This can cause state from one list item to appear in another, leading to confusing bugs such as inputs retaining wrong values or toggles switching unexpectedly.
Why Interviewers Ask This
This is a high-signal question that reveals real-world debugging experience.
Common Mistakes
Blaming React state bugs without checking key usage.
How should keys be handled when rendering nested lists?
Each level of a nested list requires its own set of unique keys relative to its sibling elements. Keys should be applied at the level where the map() is executed to ensure proper reconciliation at every depth.
Why Interviewers Ask This
Tests complex rendering scenarios and hierarchical thinking.
What are real-world scenarios where incorrect keys cause production bugs?
Incorrect keys commonly cause issues in sortable lists, drag-and-drop interfaces, editable tables, and animated lists. Symptoms include mismatched UI state, flickering components, and unexpected re-renders that are difficult to debug.
Why Interviewers Ask This
Interviewers use this question to assess production-level experience with React.
Common Mistakes
Failing to connect UI anomalies with key misconfiguration.
Props (short for properties) are read-only inputs passed from a parent component to a child component. They allow components to receive data and configuration, making components reusable and dynamic.
function Greeting({ name }) {
return <h1>Hello {name}</h1>;
}
Why Interviewers Ask This
Interviewers ask this to verify understanding of React’s data flow and component communication.
Common Mistakes
Confusing props with state or trying to modify props inside a child component.
State is a built-in mechanism that allows components to store and manage data that can change over time and trigger re-rendering of the UI when updated.
Why Interviewers Ask This
Interviewers ask this to ensure the candidate understands React’s reactive data model.
What is the useState hook and what does it return?
useState is a React Hook that lets functional components manage state. It returns an array containing the current state value and a function to update it.
Directly mutating state does not notify React about the change, which can lead to inconsistent UI and bugs. State must be updated using the setter function.
Why Interviewers Ask This
Interviewers look for understanding of immutability and React internals.
What is the functional form of setState in useState?
The functional form accepts a function that receives the previous state and returns the next state. It is useful when the new state depends on the previous state.
setCount(prevCount => prevCount + 1);
Why Interviewers Ask This
Tests understanding of asynchronous state updates.
What happens when state updates cause a re-render?
When state changes, React re-executes the component function, compares the new virtual DOM with the previous one, and updates only the necessary parts of the real DOM.
Why Interviewers Ask This
Checks understanding of reconciliation and rendering.
Custom hooks are functions that encapsulate reusable stateful logic using existing hooks. They improve code reuse, separation of concerns, and testability without altering component structure.
Custom hooks must follow the Rules of Hooks: they must be called at the top level and only from React components or other hooks. This ensures React can track hook order correctly.
What is the difference between useLayoutEffect and useEffect in React?
`useEffect` runs after the component renders and the browser has painted, making it suitable for side effects like data fetching, subscriptions, or logging. `useLayoutEffect` runs synchronously after all DOM mutations but before the browser paints, allowing updates to layout, measurements, or DOM manipulations that need to happen before the user sees the UI. Using `useLayoutEffect` incorrectly can block the paint and cause jank.
When should you use useReducer instead of useState in React?
`useReducer` is useful for managing complex state logic where state transitions depend on previous state or involve multiple sub-values. It provides a predictable state update pattern using a reducer function, similar to Redux but at component level. This is particularly valuable in forms, multi-step wizards, or when replacing Redux-like logic locally.
// Usage:
dispatch({ type: "increment" });
Why Interviewers Ask This
Assesses the ability to design maintainable and scalable state management in React components.
Common Mistakes
Overcomplicating simple state by using useReducer unnecessarily, or mismanaging the reducer function structure.
useCallback memoizes function references so they are not recreated on every render. This is important when passing callbacks to memoized child components to prevent unnecessary re-renders.
useContext allows components to consume shared data without prop drilling. It is commonly used for global concerns like themes, authentication, or localization where passing props through many layers becomes cumbersome.
const theme = useContext(ThemeContext);
Why Interviewers Ask This
Interviewers check architectural thinking and state distribution.
Common Mistakes
Using context for frequently changing data leading to unnecessary re-renders.
When context value changes, all consuming components re-render. Without memoization or context splitting, this can cause performance issues. Proper context design minimizes unnecessary updates.
useEffect is used to perform side effects in functional components such as data fetching, subscriptions, or manual DOM manipulation. By default, it runs after the component renders, ensuring the UI is committed before side effects execute.
useEffect(() => { fetchData(); }, []);
Why Interviewers Ask This
Interviewers test understanding of side effects vs rendering.
Common Mistakes
Performing side effects directly inside render logic.
How does the dependency array control useEffect execution?
The dependency array tells React when to re-run the effect by tracking value changes via reference equality. If a dependency changes, React cleans up the previous effect and runs it again, ensuring state and effects stay in sync.
Why Interviewers Ask This
This reveals deep understanding of closures, identity, and synchronization.
Common Mistakes
Omitting dependencies or disabling lint rules instead of fixing logic.
useMemo memoizes expensive calculations to avoid recomputation on every render. It should be used when a calculation is costly and its dependencies change infrequently.
useMemo(() => expensiveCalc(data), [data]);
Why Interviewers Ask This
Interviewers want to avoid premature optimization.
Common Mistakes
Using useMemo everywhere without performance justification.
useRef provides a mutable container that persists across renders without causing re-renders. It is commonly used to access DOM elements or store mutable values like timers or previous state.
useRef does not trigger re-renders when updated, whereas useState does. This makes refs ideal for storing non-UI mutable values, while state should be used for data that affects rendering.
What problem does the useState hook solve in React?
useState allows functional components to manage internal state. Before hooks, state was only available in class components. useState enables stateful logic inside functional components, making components simpler, more reusable, and easier to reason about.
const [count, setCount] = useState(0);
Why Interviewers Ask This
Interviewers ask this to ensure the candidate understands why hooks exist, not just how to use them.
Common Mistakes
Thinking useState is only a replacement for setState without understanding functional updates.
State updates in React are batched for performance. When setState is called, React schedules an update rather than applying it immediately. This ensures fewer re-renders and predictable reconciliation.
Why Interviewers Ask This
Tests understanding of rendering lifecycle and batching.
Common Mistakes
Expecting state to update immediately after calling the setter.
What problem does the Context API solve in state management?
The Context API solves prop drilling by allowing data to be shared across component trees without manually passing props through each level. It is best suited for low-frequency, broadly shared data.
const value = useContext(MyContext);
Why Interviewers Ask This
Interviewers assess understanding of built-in React tools.
Common Mistakes
Using Context as a replacement for all state management.
Why is Context API not a full state management solution?
Context does not provide built-in mechanisms for state normalization, caching, middleware, or advanced debugging. Frequent updates to context can cause widespread re-renders, making it unsuitable for high-frequency state changes.
Why Interviewers Ask This
This checks whether candidates understand limitations.
What is the difference between local state and global state in React?
Local state is owned and managed by a single component and affects only its internal UI. Global state is shared across multiple components and represents application-wide concerns such as user authentication, theme, or cached server data.
Why Interviewers Ask This
Interviewers want to evaluate understanding of state ownership and scope.
How do you decide whether state should be local or global?
State should be local if it is used by a single component or tightly coupled to its UI. It should be global only when multiple distant components require access or synchronization. Elevating state too early increases complexity and cognitive load.
Why Interviewers Ask This
This tests architectural judgment.
Common Mistakes
Assuming global state management is inherently better.
Redux should not be used for local UI state, simple forms, or applications with minimal shared state. Introducing Redux unnecessarily increases cognitive load, code complexity, and maintenance overhead.
Why Interviewers Ask This
This is a high-signal question that reveals seniority.
What problems does Redux Toolkit solve compared to classic Redux?
Redux Toolkit reduces boilerplate by providing utilities like createSlice and createAsyncThunk. It enforces best practices by default, simplifies immutable updates, and improves developer experience.
Redux is suitable for large applications with complex shared state, predictable data flow requirements, and the need for advanced debugging, caching, or middleware. It excels in scenarios where state changes must be traceable and deterministic.
Why Interviewers Ask This
This tests real-world experience.
Common Mistakes
Introducing Redux for small or simple applications.
How do you design a state management strategy for a large React application?
A robust strategy uses a combination of local state, Context for low-frequency shared data, and external state libraries for complex global concerns. Senior engineers prioritize simplicity, scalability, and team clarity over tooling preferences.
Why Interviewers Ask This
This distinguishes senior engineers from framework users.
Why might a team choose Zustand or Recoil over Redux?
Modern alternatives like Zustand or Recoil offer simpler APIs, reduced boilerplate, and more granular subscriptions. They are often easier to adopt while still supporting global state patterns.
Why Interviewers Ask This
Interviewers want awareness of evolving ecosystem.
Common Mistakes
Choosing a library based on popularity rather than fit.
How do you decide which component pattern to use in a large React application?
The choice depends on data ownership, frequency of updates, reuse requirements, and team conventions. Senior engineers balance simplicity, performance, and maintainability rather than following rigid patterns.
Why Interviewers Ask This
This question distinguishes senior engineers from mid-level developers.
Common Mistakes
Applying patterns dogmatically without considering context.
The compound components pattern allows multiple components to work together while sharing implicit state via context. It provides a flexible and expressive API while keeping related logic encapsulated.
Why Interviewers Ask This
This reveals advanced component API design skills.
Common Mistakes
Overusing compound patterns for simple components.
Q 4.1.3 //
Intermediate • Controlled vs Uncontrolled Components
What is the difference between controlled and uncontrolled components in React?
Controlled components derive their value from React state and update through event handlers, making the React component the single source of truth. Uncontrolled components rely on the DOM to manage state internally, typically accessed via refs.
Q 4.1.4 //
Advanced • Controlled vs Uncontrolled Components
When would you choose an uncontrolled component over a controlled one?
Uncontrolled components are suitable for simple forms, performance-sensitive inputs, or when integrating with non-React libraries. They reduce re-rendering overhead but sacrifice fine-grained control.
const inputRef = useRef();
Why Interviewers Ask This
This tests practical decision-making rather than rigid rules.
Common Mistakes
Believing controlled components are always superior.
Lifting state up refers to moving shared state to the closest common ancestor so that multiple components can stay synchronized. This establishes a clear data flow and prevents duplicated or conflicting state.
Why Interviewers Ask This
Interviewers want to see understanding of data flow design.
What are the downsides of excessive state lifting?
Excessive lifting can lead to bloated parent components, unnecessary re-renders, and prop drilling. At scale, it can harm readability and maintainability, indicating a need for better state distribution strategies.
Why Interviewers Ask This
Tests architectural maturity.
Common Mistakes
Using lifting as the only state management strategy.
Q 4.1.7 //
Intermediate • Presentational vs Container Components
What is the difference between presentational and container components?
Presentational components focus on how things look and receive data via props, while container components handle logic, data fetching, and state management. This separation improves reusability and testability.
Q 4.1.8 //
Intermediate • Props Drilling vs Context API
What is prop drilling and when does it become a problem?
Prop drilling occurs when data is passed through many layers of components that do not directly use it. It becomes problematic when it increases coupling, reduces readability, and makes refactoring difficult.
Why Interviewers Ask This
Tests awareness of maintainability issues.
Common Mistakes
Using context immediately without evaluating component structure.
Q 4.1.9 //
Advanced • Props Drilling vs Context API
When should Context API be preferred over prop drilling?
Context should be used when data is truly global or widely shared, such as themes or authentication state. Overusing context can harm performance and obscure data flow.
A reusable component is flexible, predictable, and decoupled from specific business logic. It exposes configuration through props, avoids hard-coded dependencies, and focuses on a single responsibility.
Why Interviewers Ask This
Interviewers want insight into scalable UI design.
Common Mistakes
Overgeneralizing components and making APIs too complex.
Lazy loading routes reduces initial bundle size by loading route components only when needed. React.lazy combined with Suspense enables code splitting at the route level.
const Page = React.lazy(() => import("./Page"));
Why Interviewers Ask This
Performance optimization is a strong senior signal.
Nested routes allow rendering child routes within parent layouts. They help organize UI structure and share common layout components like headers or sidebars.
Protected routes are implemented by conditionally rendering route elements based on authentication state. If unauthorized, users are redirected using <Navigate>.
React Router maps URLs to React components, enabling navigation and deep linking in Single Page Applications. It keeps the UI in sync with the browser URL.
Why Interviewers Ask This
This checks foundational routing knowledge.
Common Mistakes
Manually handling routing logic with window.location.
Explain the difference between <BrowserRouter> and <HashRouter>.
BrowserRouter uses the HTML5 history API for clean URLs, while HashRouter uses URL hashes (#) and works without server-side configuration. BrowserRouter is preferred for production when server support is available.
<BrowserRouter><App /></BrowserRouter>
Why Interviewers Ask This
Interviewers assess deployment awareness.
Common Mistakes
Using BrowserRouter without server fallback configuration.
Route parameters allow dynamic values in the URL, accessed using the useParams hook. They enable reusable routes such as user profiles or product pages.
What is client-side routing in a Single Page Application?
Client-side routing allows navigation between different views without reloading the page. Instead of requesting new HTML from the server, the browser updates the URL and React renders different components based on the route, resulting in faster transitions and better user experience.
Why Interviewers Ask This
Interviewers want to ensure understanding of SPA fundamentals.
Common Mistakes
Confusing client-side routing with traditional server-side routing.
A controlled form component is one where form input values are managed by React state. Every change triggers a state update, making React the single source of truth for the form data.
What are the advantages and disadvantages of controlled forms?
Controlled forms offer better validation, predictable state, and easier debugging. However, they can introduce performance overhead for large forms due to frequent re-renders.
Why Interviewers Ask This
Tests trade-off analysis.
Common Mistakes
Using controlled inputs everywhere without considering scale.
Q 6.1.3 //
Intermediate • Controlled vs Uncontrolled Forms
When would you prefer uncontrolled components over controlled ones?
Uncontrolled components are useful for simple forms or when integrating with non-React libraries. They rely on refs instead of state, reducing re-renders.
How do you manage loading and submission states in forms?
Submission state is managed using flags such as isSubmitting or loading indicators. Disabling buttons and showing progress feedback prevents duplicate submissions.
Why are form libraries like React Hook Form or Formik used?
Form libraries reduce boilerplate, improve performance, and provide structured validation and error handling. React Hook Form is especially popular due to its minimal re-renders.
Why Interviewers Ask This
Tests familiarity with industry tools.
Common Mistakes
Using custom form logic when libraries would simplify.
What are common form-related anti-patterns in React applications?
Common anti-patterns include deeply nested form state, duplicating validation logic, ignoring accessibility, and overusing local state instead of form libraries.
Schema-based validation uses libraries like Yup or Zod to define form validation rules declaratively. This improves maintainability and consistency across forms.
What are common anti-patterns when fetching data in React?
Anti-patterns include: fetching data directly inside render, failing to cancel subscriptions on unmount, over-fetching the same data, and poor caching strategies. Avoiding these ensures maintainable, performant applications.
Why Interviewers Ask This
Tests architectural maturity.
Common Mistakes
Triggering multiple identical requests due to missing dependency arrays.
How does caching and revalidation work in React Query?
React Query caches fetched data to avoid unnecessary requests. Revalidation ensures data freshness by refetching in the background when the component mounts or at specified intervals. It helps maintain a balance between performance and data accuracy.
queryClient.invalidateQueries("todos");
Why Interviewers Ask This
Interviewers check understanding of optimized server-state management.
Common Mistakes
Not invalidating stale data or manually refreshing unnecessarily.
How do you handle API errors in React applications effectively?
API errors should be caught and displayed to the user. Retry mechanisms, toast notifications, and fallback UI improve UX. Using libraries like Axios interceptors or React Query error handling simplifies global error handling.
How do you fetch data from an API in React using fetch or Axios?
Data can be fetched using the browser fetch API or Axios library. Typically, the request is triggered inside useEffect to ensure it runs after component mount. Axios provides additional features like automatic JSON parsing and request cancellation.
Q 7.1.5 //
Intermediate • Loading, Error, Success States
How should loading, error, and success states be managed when fetching data?
These states should be managed in local state (or React Query) to provide clear user feedback. For example: isLoading, isError, and data. Proper handling prevents displaying stale or partial data and improves UX.
How do you implement pagination or infinite scroll in React?
Pagination is implemented by requesting data in chunks using page numbers or cursors. Infinite scroll detects when the user reaches the bottom of the list and triggers additional API calls. This improves performance and reduces initial load time.
window.addEventListener("scroll", handleScroll);
Why Interviewers Ask This
Tests performance optimization and real-world UI handling.
What is React Query and why use it over traditional fetching?
React Query (TanStack Query) provides caching, background updates, query invalidation, pagination, and request deduplication. It abstracts away boilerplate and ensures consistent server state management.
Why do we often use useEffect for API calls in React?
useEffect allows you to perform side effects in functional components. Placing API calls inside useEffect ensures they are executed after the component has mounted, avoiding repeated calls on each render.
useEffect(() => { fetchData(); }, []);
Why Interviewers Ask This
Tests understanding of React’s rendering lifecycle.
What are the differences between CSS and SCSS in React projects?
CSS is a standard styling language; SCSS extends CSS with variables, nesting, and mixins. SCSS improves maintainability, reduces repetition, and allows modular organization of styles in React apps.
What are the risks of using global CSS in React apps?
Global CSS can cause style collisions, specificity wars, and unintended overrides across components. Large applications become hard to maintain without proper modularization.
body { font-family: Arial; }
Why Interviewers Ask This
Assesses understanding of potential pitfalls in styling React apps.
Common Mistakes
Using global CSS indiscriminately leading to bugs and overrides.
How do CSS Modules prevent style conflicts in React?
CSS Modules automatically scope class names locally per component. Each class name is hashed at build time, preventing collisions and ensuring component-level style isolation.
import styles from "./Button.module.css";
<button className={styles.primary}>Click</button>;
Why Interviewers Ask This
Tests knowledge of modular and maintainable styling patterns.
Common Mistakes
Importing module incorrectly or forgetting to use generated classNames.
Q 8.1.4 //
Intermediate • CSS Modules vs Styled Components
What are the main differences between CSS Modules and Styled Components?
CSS Modules keep CSS in separate files, scoped to components. Styled Components allow writing CSS inside JS files with dynamic props, theming, and runtime style evaluation. Choice depends on team preference, dynamic styling needs, and theming requirements.
When should you use inline styles instead of CSS Modules or Styled Components?
Inline styles are suitable for dynamic values, small style adjustments, or conditional styling. For large static styles, CSS Modules or Styled Components are preferred for maintainability and readability.
How do you create a styled component and pass dynamic props?
Styled Components allows defining component-level styles. Props can be used for dynamic styling, e.g., color, padding. This reduces the need for multiple CSS classes and improves readability.
How can theming be implemented with Styled Components?
Styled Components provides a ThemeProvider. Define a theme object (colors, fonts) and pass it down to components. Components access theme via props or helper functions. This allows consistent theming across the app.
What are common performance pitfalls in styling React components?
Re-rendering components with inline style objects, frequent dynamic className changes, or heavy CSS-in-JS computations can hurt performance. Memoizing styles or using CSS Modules/Styled Components efficiently mitigates these issues.
How do you use Tailwind CSS in React for utility-first styling?
Tailwind CSS uses utility classes directly in className. This enables rapid UI development with a consistent design system. Classes control padding, margin, color, font, etc., without writing separate CSS.
How does Tailwind handle responsive design in React?
Tailwind provides responsive prefixes (sm:, md:, lg:, xl:) to apply classes at specific breakpoints. Combining them allows building fully responsive components declaratively in JSX.
<div className="p-2 sm:p-4 md:p-6">Content</div>
Why Interviewers Ask This
Evaluates ability to handle mobile-first and responsive UI.
Common Mistakes
Ignoring mobile breakpoints or duplicating classes unnecessarily.
What are the advantages of using UI libraries like MUI, AntD, or Chakra?
UI libraries provide pre-built, accessible, and responsive components, consistent theming, and reduce development time. They also often include dark mode support and ready-to-use design patterns.
import { Button } from "@mui/material";
<Button variant="contained">Click Me</Button>;
Why Interviewers Ask This
Assesses practical production experience with component libraries.
Common Mistakes
Over-customizing components or ignoring the library’s theming system.
How do you customize components in UI libraries while maintaining theming?
Use provided theming APIs (ThemeProvider, styled overrides) instead of overriding CSS. This ensures consistency, maintainability, and avoids breaking library updates.
How can you prevent unnecessary re-renders in React components?
Strategies include: using React.memo for functional components, splitting large components into smaller ones, memoizing expensive calculations with useMemo, memoizing callbacks with useCallback, and ensuring proper key usage in lists.
Why Interviewers Ask This
Tests practical knowledge of render performance tuning.
Common Mistakes
Not splitting large components, causing all children to re-render frequently.
How do code splitting and lazy loading improve React app performance?
Code splitting allows you to break the bundle into smaller chunks, loading only what is needed. React.lazy and Suspense enable lazy loading of components, which reduces initial load time and improves perceived performance.
Why is the key prop important when rendering lists in React?
The key prop helps React identify which items have changed, are added, or removed. Using a stable key improves reconciliation performance and prevents unnecessary re-renders of list items.
What is React.memo and how does it improve performance?
React.memo is a higher-order component that memoizes a functional component. It prevents unnecessary re-renders by shallowly comparing props, so the component only re-renders when its props change.
export default React.memo(MyComponent);
Why Interviewers Ask This
Interviewers want to test understanding of re-render optimizations in functional components.
Common Mistakes
Using React.memo indiscriminately on all components without considering prop complexity or functions inside props.
How does useCallback differ from useMemo and when should it be used?
useCallback memoizes a function reference so that it does not change between renders unless its dependencies change. This is particularly useful when passing callbacks to child components wrapped with React.memo to avoid unnecessary re-renders.
When and why would you use useMemo in a component?
useMemo memoizes the result of a computation between renders. It is useful for expensive calculations that do not need to be recalculated unless dependencies change, preventing unnecessary performance overhead.
Redux itself is synchronous. Asynchronous logic is handled via middleware such as redux-thunk, which allows dispatching functions that perform async operations and then dispatch synchronous actions based on results.
Middleware sits between dispatching an action and the reducer. It enables logging, async logic, error handling, and side effects without breaking Redux’s core principles.
const logger = store => next => action => next(action);
Why Interviewers Ask This
Interviewers assess system extensibility understanding.
Q 10.1.4 //
Intermediate • Core Principles & Data Flow
What are the three core principles of Redux?
Redux is built on three principles: Single source of truth (the entire application state lives in one store), state is read-only (state can only be changed via actions), and changes are made with pure functions (reducers). These principles ensure predictability, traceability, and easier debugging.
Why Interviewers Ask This
Interviewers check whether candidates understand why Redux exists, not just how to use it.
Common Mistakes
Reciting principles without understanding their practical impact.
Q 10.1.5 //
Advanced • Core Principles & Data Flow
Explain the Redux data flow step by step.
Redux follows a unidirectional data flow: a UI event dispatches an action, the reducer processes the action and returns a new state, the store updates, and subscribed UI components re-render based on the updated state. This strict flow ensures state changes are predictable and traceable.
How do you decide if Redux is the right choice for a project?
Redux is appropriate when the application has complex shared state, needs predictable updates, benefits from debugging tools, or requires advanced async handling. Senior engineers evaluate cost vs benefit before introducing Redux.
Common anti-patterns include storing derived state, duplicating server state unnecessarily, overusing Redux for local UI concerns, and creating overly complex store structures.
Q 10.1.8 //
Intermediate • Redux Toolkit & Modern Patterns
What problems does Redux Toolkit solve?
Redux Toolkit reduces boilerplate by providing utilities like createSlice, configureStore, and built-in Immer support. It enforces best practices by default and eliminates common Redux pain points such as manual action types and immutable update complexity.
Q 10.1.9 //
Advanced • Redux Toolkit & Modern Patterns
Why is Immer important in Redux Toolkit?
Immer allows developers to write code that looks mutable while maintaining immutability under the hood. This improves readability, reduces bugs, and makes reducer logic easier to reason about.
state.count += 1;
Why Interviewers Ask This
Checks understanding of immutability and developer ergonomics.
Q 10.1.10 //
Advanced • Redux Toolkit & Modern Patterns
What does configureStore provide over createStore?
configureStore automatically sets up Redux DevTools, applies recommended middleware, enables better defaults, and simplifies store configuration. It represents the modern standard for creating Redux stores.
How do you test asynchronous behavior in React components?
Use async/await with RTL utilities like waitFor or findBy*. Ensure promises resolve and DOM updates are asserted correctly. Avoid using setTimeout in tests directly.
What are common mistakes in testing React applications?
Common mistakes include over-testing implementation details, not testing user interactions, using real APIs, and ignoring async updates. Avoid brittle tests by focusing on behavior and output rather than internal state.
// Conceptual best-practice guidance, no code needed
Why Interviewers Ask This
Checks awareness of best practices and potential traps.
Common Mistakes
Writing tests that break on any small internal refactor or DOM change.
How do you test components that rely on React Context?
Wrap the component under test in the context provider and provide mock values. This ensures the component behavior can be tested without relying on actual app context.
React Testing Library provides fireEvent and userEvent to simulate clicks, typing, and other interactions. Tests should assert the result of user actions, such as DOM updates or function calls.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Click</Button>);
userEvent.click(screen.getByText("Click"));
expect(handleClick).toHaveBeenCalled();
Why Interviewers Ask This
Tests ability to verify real user interactions.
Common Mistakes
Testing implementation functions instead of visible outcomes.
How do you test controlled forms and validation in React?
Controlled form inputs can be tested by changing their value using fireEvent or userEvent, then asserting validation messages or form state updates. Libraries like React Hook Form and Formik provide testing utilities.
What is Jest and why is it commonly used with React?
Jest is a JavaScript testing framework developed by Facebook. It provides zero-configuration setup, snapshot testing, mocks, timers, and code coverage. It integrates seamlessly with React for unit and integration tests.
// Example Jest test
import { sum } from "./utils";
test("adds 1 + 2 to equal 3", () => {
expect(sum(1,2)).toBe(3);
});
Why Interviewers Ask This
Tests familiarity with standard React testing tools.
Common Mistakes
Confusing Jest with other testing frameworks, or not using its mocking capabilities.
What is snapshot testing and when should it be used?
Snapshot testing captures a rendered component's output and compares it to a stored snapshot. Useful for detecting unexpected UI changes. Should be used for stable, presentational components, not dynamic data-heavy ones.
import { render } from "@testing-library/react";
import renderer from "react-test-renderer";
const tree = renderer.create(<Button>Click</Button>).toJSON();
expect(tree).toMatchSnapshot();
Why Interviewers Ask This
Tests knowledge of Jest snapshot feature and appropriate usage.
Common Mistakes
Overusing snapshots for frequently changing components causing unnecessary failures.
What is React Testing Library and how is it different from Enzyme?
React Testing Library (RTL) focuses on testing components from a user perspective rather than implementation details. Unlike Enzyme, which exposes internal component state, RTL encourages testing DOM interactions, accessibility, and behavior.
import { render, screen } from "@testing-library/react";
render(<Button>Click</Button>);
screen.getByText("Click");
Why Interviewers Ask This
Tests understanding of modern testing best practices in React.
Common Mistakes
Testing internal state or implementation details instead of user interactions.
Testing ensures code correctness, prevents regressions, and allows refactoring with confidence. It also improves maintainability, reliability, and developer productivity in production applications.
// Conceptual question, no code required
Why Interviewers Ask This
Evaluates understanding of testing philosophy and best practices.
Common Mistakes
Skipping tests or relying only on manual QA, leading to undetected bugs.
Custom hooks can be tested using RTL's renderHook utility from @testing-library/react-hooks or wrapping the hook inside a test component. Tests focus on state changes, side effects, and return values.
import { renderHook, act } from "@testing-library/react-hooks";
const { result } = renderHook(() => useCounter());
act(() => result.current.increment());
expect(result.current.count).toBe(1);
Why Interviewers Ask This
Assesses knowledge of advanced testing techniques for hooks.
Common Mistakes
Testing hooks outside of React context or ignoring side effects.
How do you mock API calls in component or hook tests?
API calls can be mocked using Jest's jest.mock(), mock service worker (MSW), or libraries like axios-mock-adapter. This isolates components/hooks from network and allows predictable test outcomes.
jest.mock("axios");
import axios from "axios";
axios.get.mockResolvedValue({ data: [] });
Why Interviewers Ask This
Tests practical skills in isolating components for testing.
Common Mistakes
Calling real APIs in tests leading to flaky or slow tests.
What is the difference between unit tests and integration tests in React?
Unit tests verify individual functions or components in isolation. Integration tests verify that multiple components work together correctly, including API calls, context, and child components. Both are essential for reliable applications.
// Unit test: test Button renders
// Integration test: test Button inside Form with context
Why Interviewers Ask This
Evaluates understanding of testing scope and strategy.
Common Mistakes
Writing only unit tests without integration coverage, missing interactions.
What is React Strict Mode and why should it be used?
React Strict Mode is a tool for highlighting potential problems in an application during development. It does not render any visible UI but activates additional checks and warnings for deprecated APIs, unsafe lifecycles, and side effects. Using Strict Mode helps identify issues early and promotes better coding practices.
// Wrap your app
<React.StrictMode>
<App />
</React.StrictMode>
Why Interviewers Ask This
Tests understanding of proactive debugging and code quality improvement in React.
Common Mistakes
Confusing Strict Mode with production behavior; expecting it to affect runtime in production (it only affects development).
Why does React double-invoke certain functions and lifecycle methods in Strict Mode during development?
Strict Mode intentionally double-invokes functions such as component constructors, render, and effects (useEffect, useState setters) in development. This helps detect side-effects that may be unsafe or impure, ensuring components are resilient and side-effect-free.
// Example: useEffect will run twice in development
useEffect(() => {
console.log("Effect runs");
}, []);
Why Interviewers Ask This
Assesses deeper understanding of React internals and lifecycle behavior.
Common Mistakes
Assuming double invocation is a bug, leading to unnecessary debugging.
How does Strict Mode affect component lifecycle and behavior?
Strict Mode does not alter production behavior but affects development lifecycle: constructors, render, and useEffect are called twice; legacy lifecycle methods may trigger warnings. This encourages pure functions, safe side-effects, and helps detect accidental mutations.
Why Interviewers Ask This
Tests ability to reason about lifecycle impacts and debugging implications.
Common Mistakes
Ignoring warnings or side-effects detected by Strict Mode can lead to bugs in production.
What is React DevTools Profiler and how is it used for performance debugging?
React DevTools Profiler allows developers to record performance of component renders. It shows the time spent in rendering each component, highlighting expensive renders and unnecessary re-renders. By analyzing the profiler data, developers can optimize rendering, memoize components, or refactor state management.
// In browser, open React DevTools > Profiler > Record interactions to measure component render time.
Why Interviewers Ask This
Tests practical performance debugging skills and optimization knowledge.
Common Mistakes
Relying on console.log for performance measurement or ignoring expensive renders.
How can you inspect the render count of a component and why is it important?
Render count helps identify unnecessary re-renders which may affect performance. Using React DevTools or console tracking inside the component helps measure renders. High render counts may indicate improper state management, lack of memoization, or unoptimized props.
How do you profile render cost and optimize expensive components in React?
Profiling render cost involves using React DevTools Profiler to measure the time each component takes to render. After identifying expensive components, optimizations include React.memo, useMemo, useCallback, splitting components, or lazy-loading. Profiling ensures smooth UI and prevents unnecessary re-renders.
// Example: wrapping component in React.memo to avoid unnecessary renders
const OptimizedComponent = React.memo(function Component({ data }) { return <div>{data}</div>; });
Why Interviewers Ask This
Tests ability to perform performance analysis and apply optimization patterns.
Common Mistakes
Optimizing without profiling, or prematurely memoizing components without identifying true bottlenecks.
What is concurrent rendering in React and why is it important?
Concurrent rendering is a feature that allows React to interrupt long-running rendering tasks to keep the UI responsive. It enables React to prioritize urgent updates (like user input) over less critical ones. This leads to smoother user experiences, especially in large applications.
// Conceptual, but usage example: enable Concurrent Mode in React 18
import { createRoot } from "react-dom/client";
const root = createRoot(document.getElementById("root"));
root.render(<App />);
Why Interviewers Ask This
Evaluates understanding of modern performance and responsiveness techniques.
Common Mistakes
Assuming all renders are synchronous, leading to poor responsiveness in complex apps.
How does concurrent mode differ from traditional React rendering?
Traditional rendering is synchronous: React processes updates one at a time, blocking the main thread. Concurrent Mode splits rendering into multiple units and can pause, resume, or prioritize updates without blocking the UI, improving responsiveness.
What are Error Boundaries in React and how do you use them?
Error Boundaries are React components that catch JavaScript errors in their child component tree during rendering, lifecycle methods, and constructors. They prevent the whole app from crashing and allow showing fallback UI.
What are best practices for error handling with Error Boundaries?
Always place Error Boundaries around high-level UI blocks, provide fallback UI, log errors to monitoring services, and avoid swallowing errors silently. Consider combining with logging tools for production readiness.
Can Error Boundaries catch errors in Suspense fallbacks?
Error Boundaries can catch errors during rendering but not errors in event handlers or asynchronous code. When using Suspense, the fallback renders while waiting; errors inside lazy components can still be caught by Error Boundaries.
What are Server Components in React (Next.js) and how do they differ from client components?
Server Components are rendered on the server and sent as HTML to the client. They reduce bundle size and improve performance because heavy logic does not need to run in the browser. Client components handle interactivity, while server components handle static rendering and data fetching.
// Example in Next.js 13+
export default function ServerComponent() {
const data = await fetch("/api/data").then(res => res.json());
return <div>{data.title}</div>;
}
Why Interviewers Ask This
Assesses knowledge of modern SSR strategies and performance optimization.
Common Mistakes
Confusing server and client components leading to unnecessary client-side rendering.
Streaming allows the server to send parts of the HTML as they are rendered, reducing Time to First Byte (TTFB) and showing content faster. Partial hydration hydrates only interactive parts of the page, saving CPU and improving perceived performance.
// Conceptual example with Next.js 13
export default function Page() {
return (
<Suspense fallback={<Loading />}>
<ServerComponent />
</Suspense>
);
}
Why Interviewers Ask This
Evaluates understanding of advanced server-client rendering optimizations.
Common Mistakes
Hydrating the whole page unnecessarily, leading to slow performance.
Streaming reduces time to first meaningful paint, allows the browser to progressively render content, and improves user perception of speed, especially for large pages with heavy data.
// Conceptual example
export default function Page() {
return <ServerComponent />;
}
Why Interviewers Ask This
Checks understanding of performance optimizations in real-world apps.
Common Mistakes
Sending the whole HTML at once causing slower perceived load.
How is partial hydration applied in modern React apps?
Partial hydration hydrates only interactive components on the client, leaving static content untouched. This reduces JS execution, improves performance, and works well with server-rendered apps like Next.js.
// Example: hydrate only interactive parts
<InteractiveWidget />
Why Interviewers Ask This
Tests knowledge of practical optimizations and server-client rendering balance.
What is React Suspense and how does it help with data fetching?
Suspense allows components to "wait" for asynchronous operations (like API calls or lazy-loaded components) and display fallback content in the meantime. It simplifies handling loading states and improves user experience by coordinating UI readiness.
Suspense allows lazy-loaded components to display fallback content while the chunk is being fetched. This enables splitting the application bundle into smaller pieces and loading only what is needed.
Q 13.1.12 //
Advanced • Suspense + Server Components
How do Suspense and Server Components work together in Next.js?
Suspense handles async rendering of server components. Server components fetch data on the server, and Suspense shows fallback UI while waiting. This combination improves performance, reduces client bundle size, and ensures smooth UX.
What are Render Props in React and how do they help in component reuse?
Render Props is a pattern where a component takes a function as a prop to determine what to render. It allows sharing behavior between components without repeating code. The component using a render prop can pass any data or state to the function, making it highly reusable.
// Component definition
function DataProvider({ render }) {
const data = ["item1","item2"];
return render(data);
}
Why Interviewers Ask This
Tests knowledge of advanced composition patterns and component reusability.
Common Mistakes
Confusing Render Props with HOCs or not properly passing props to the render function.
What are Higher-Order Components (HOCs) and why are they used?
HOCs are functions that take a component and return a new component with additional props or behavior. They enable code reuse, cross-cutting concerns like logging, error boundaries, or injecting global state without modifying the original component.
What is React.forwardRef and when should it be used?
React.forwardRef is a technique for passing a ref through a component to one of its child DOM elements. This is useful for exposing DOM nodes to parent components, handling focus, or integrating with third-party libraries that require refs.
Portals provide a way to render children into a DOM node outside the parent component hierarchy. They are often used for modals, tooltips, or popovers where UI elements must visually break out of container boundaries while keeping React state and events intact.
// The component remains controlled by React
function Modal() { return <div className="modal">Hello</div>; }
Why Interviewers Ask This
Tests knowledge of advanced DOM rendering strategies and practical UI patterns.
Common Mistakes
Attempting to manually manipulate the DOM outside React or ignoring event bubbling across portals.
How do you build and deploy a React or Next.js application?
For CRA: run npm run build to generate static files in the build folder and serve using any static hosting. For Next.js: run npm run build and npm start for production SSR or deploy to platforms like Vercel for automatic SSR/SSG handling.
// CRA build
npm run build
// Next.js build
npm run build && npm start
Why Interviewers Ask This
Evaluates understanding of production readiness and deployment strategies.
Common Mistakes
Skipping build optimization or using development server in production.
What are best practices for continuous deployment of React apps?
Use CI/CD pipelines, automated tests, environment-specific builds, code reviews, and version control. Platforms like Vercel, Netlify, or GitHub Actions simplify deployment and rollback in case of errors.
// Example CI workflow
name: Deploy
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npm run build
- run: npm run deploy
Why Interviewers Ask This
Assesses readiness for professional software engineering workflows.
Common Mistakes
Deploying manually without tests or version control, leading to downtime or errors.
How do you use environment variables in React applications?
Environment variables allow you to store sensitive or environment-specific information (API keys, endpoints). In CRA, variables must start with REACT_APP_. In Next.js, you can define variables in .env.local or .env.production, and use process.env.VARIABLE_NAME.
// CRA example
const apiUrl = process.env.REACT_APP_API_URL;
// Next.js example
const apiKey = process.env.API_KEY;
Why Interviewers Ask This
Tests understanding of configuration management and security practices.
Common Mistakes
Exposing sensitive keys directly in client-side code or forgetting REACT_APP_ prefix in CRA.
How does a production environment differ from development in React?
In production, React disables development warnings, minifies JS, and optimizes performance. Environment variables differ (.env.production vs .env.development), and build artifacts are static files or server-optimized bundles for deployment.
// Access production environment variables
const apiUrl = process.env.REACT_APP_API_URL;
Why Interviewers Ask This
Tests understanding of environment awareness in production readiness.
Common Mistakes
Using development variables or unoptimized builds in production.
Why are ESLint and Prettier important in React projects?
ESLint enforces coding standards and catches errors early, while Prettier formats code consistently. Together, they ensure maintainable, readable, and bug-free code, which is critical for team collaboration and code quality.
// ESLint config example
{
"extends": ["react-app", "eslint:recommended"]
}
// Prettier config example
{
"semi": true,
"singleQuote": true
}
Why Interviewers Ask This
Tests knowledge of tooling that improves developer productivity and code quality.
Common Mistakes
Using only one without the other, leading to either poor formatting or missing error checks.
What is the difference between SSR (Server-Side Rendering) and SSG (Static Site Generation) in Next.js?
SSR renders pages on each request at runtime, ensuring fresh data on every page load. SSG pre-renders pages at build time, which improves performance but serves static content until next build. SSR is ideal for dynamic content, while SSG is ideal for static blogs or marketing pages.
// SSR example
export async function getServerSideProps(context) {
const data = await fetchAPI();
return { props: { data } };
}
// SSG example
export async function getStaticProps() {
const data = await fetchAPI();
return { props: { data } };
}
Why Interviewers Ask This
Tests understanding of performance and rendering strategies in modern React frameworks.
Common Mistakes
Confusing SSR with client-side rendering, leading to poor SEO or stale content.
Next.js allows dynamic routes using bracket notation in the filename (e.g., [id].js). This enables pages to handle variable URL segments and fetch data accordingly, improving scalability and SEO.
// pages/posts/[id].js
export default function Post({ data }) { return <div>{data.title}</div>; }
export async function getStaticPaths() { return { paths: [], fallback: true }; }
Why Interviewers Ask This
Assesses practical knowledge of routing in production apps.
Common Mistakes
Using query parameters incorrectly instead of file-based dynamic routes.
Next.js Image component automatically optimizes images by resizing, lazy loading, and serving in modern formats (WebP). This improves performance, reduces bandwidth, and ensures faster load times for end users.
What are Next.js API routes and why are they useful?
Next.js API routes allow you to build backend endpoints directly in your Next.js app without needing a separate server. Useful for serverless functions, handling form submissions, or simple backend logic alongside frontend.
What are the main differences between Vite and Create React App (CRA)?
Vite is a modern build tool using ES modules with extremely fast cold start and HMR (Hot Module Replacement). CRA relies on Webpack and can be slower for large apps. Vite improves development experience and build speed significantly.
What is fast refresh in Vite and why is it important?
Fast refresh allows real-time updates of React components without losing state, improving development speed and experience. Unlike CRA, Vite achieves this with ES module-based HMR, making updates near-instant.
// Vite automatically handles HMR on component save
Why Interviewers Ask This
Tests understanding of developer tooling efficiency.
Common Mistakes
Confusing fast refresh with full page reload, losing state frequently.
When would you choose Next.js over CRA for a large React application?
Next.js provides SSR, SSG, API routes, image optimization, and file-based routing. CRA is suitable for SPA only. For SEO-sensitive, data-heavy, or server-rendered apps, Next.js is preferred.
// Decision: use Next.js for SSR/SSG
// CRA for SPA projects without SSR needs
Why Interviewers Ask This
Evaluates architectural decision-making for large-scale React apps.
Common Mistakes
Using CRA for SEO-heavy or dynamic content projects, causing limitations.
What is the difference between Virtual DOM and Real DOM in React?
The Real DOM is the actual browser DOM that manipulates the UI elements and is costly to update frequently. The Virtual DOM is an in-memory lightweight representation of the Real DOM. React maintains the Virtual DOM and applies a diffing algorithm to calculate the minimal changes required, which are then efficiently applied to the Real DOM.
// Conceptual example
const vdom = React.createElement("div", null, "Hello");
// React compares this with previous VDOM to update the real DOM efficiently
Why Interviewers Ask This
Tests understanding of core React rendering optimization and performance principles.
Common Mistakes
Confusing Virtual DOM as a separate rendering engine; assuming it replaces the real DOM completely.
What is React Reconciliation and how does the diffing algorithm work?
Reconciliation is the process React uses to update the Real DOM efficiently. When state or props change, React generates a new Virtual DOM tree and compares it with the previous tree using its diffing algorithm. It then calculates the minimal set of changes (additions, deletions, updates) needed to sync the Real DOM. Key strategies include comparing element types, keys for lists, and subtree replacements.
// Example of key usage for reconciliation
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
Why Interviewers Ask This
Assesses deep understanding of React’s optimization and internal mechanisms.
Common Mistakes
Failing to use keys in lists, leading to unnecessary re-renders or incorrect reconciliation.
What is React Fiber architecture and why was it introduced?
React Fiber is a reimplementation of the React core algorithm introduced to improve rendering responsiveness and concurrency. It allows breaking rendering work into units, prioritizing updates, and pausing or resuming work to ensure high-priority updates (like user input) are handled promptly. Fiber enables features like Concurrent Mode, Suspense, and time-slicing.
// Conceptual: Fiber allows React to pause, resume, and prioritize rendering work
const element = <App />;
ReactDOM.createRoot(root).render(element);
Why Interviewers Ask This
Tests understanding of advanced React rendering internals and performance engineering.
Common Mistakes
Assuming Fiber changes the programming model for components; not understanding it only affects internal scheduling.
What are the key new features introduced in React 19?
React 19 introduces a set of features focused on simplifying async workflows, improving form handling, and enabling better user experience during transitions. Major additions include Actions for handling async mutations, new hooks like useFormStatus, useFormState, and useOptimistic, improved Suspense integration, automatic batching enhancements, and better support for Server Components. These features reduce boilerplate around loading, error, and optimistic UI states while encouraging more declarative data mutations.
Why Interviewers Ask This
Interviewers ask this to check whether the candidate is up to date with the React ecosystem and understands why React is evolving toward async-first and server-driven UI patterns.
Common Mistakes
Candidates often list features without explaining their purpose, or confuse React 19 features with earlier additions like useTransition or Suspense from previous versions.
What are Actions in React 19 and why were they introduced?
Actions in React 19 provide a built-in pattern for handling asynchronous mutations such as form submissions or data updates. An Action is an async function that React can track automatically, enabling seamless handling of loading, success, and error states. This removes the need for manual useState flags and reduces complex side-effect logic in components.
async function submitForm(formData) {
await saveUser(formData);
}
Why Interviewers Ask This
This question evaluates whether a candidate understands modern React’s move away from imperative state handling toward declarative async flows.
Common Mistakes
Many candidates think Actions are just another name for event handlers or confuse them with Redux actions, missing their async lifecycle integration.
How does useFormStatus work and what problem does it solve?
useFormStatus allows components to read the current state of a form submission, such as pending or completed, without prop drilling. It integrates tightly with Actions and enables fine-grained UI updates like disabling buttons or showing loaders while a form is submitting.
Explain useOptimistic and its role in improving user experience.
useOptimistic enables optimistic UI updates by temporarily assuming a successful result before an async operation completes. This allows the UI to feel faster and more responsive, especially in network-bound interactions. If the action fails, React can revert to the previous state.
How does React 19 improve form handling compared to earlier versions?
React 19 introduces native form Actions, useFormState, and useFormStatus, eliminating much of the boilerplate previously required for managing form submission state, validation feedback, and loading indicators. This results in simpler, more maintainable form logic.
Why Interviewers Ask This
Interviewers want to see if candidates understand how React is reducing reliance on external form libraries for common use cases.
Common Mistakes
Many candidates still default to heavy form libraries without recognizing that React now covers many built-in scenarios.
What is the relationship between React 19 and Server Components?
React 19 strengthens integration with Server Components by enabling better async boundaries, streaming, and mutation handling through Actions. Server Components allow rendering logic to run on the server, reducing bundle size and improving initial load performance.
Why Interviewers Ask This
This helps interviewers assess architectural understanding of modern full-stack React applications.
Common Mistakes
Candidates often assume Server Components replace client components entirely or misunderstand where hooks can be used.
How does React 19 improve handling of loading and error states?
With Actions and enhanced Suspense support, React 19 automatically tracks async states and propagates them through the component tree. This reduces manual error handling and makes loading states more consistent and predictable.
Why Interviewers Ask This
Interviewers ask this to see if candidates still rely on manual flags or embrace declarative async patterns.
Common Mistakes
A common mistake is mixing old loading patterns with new Action-based flows, causing redundant state.
How does React 19 change the way developers think about side effects?
React 19 encourages moving side-effect-heavy logic into Actions and server boundaries, reducing reliance on useEffect for data mutations. This leads to clearer separation between rendering and side effects.
Why Interviewers Ask This
This question distinguishes candidates who understand React’s long-term design philosophy.
Common Mistakes
Candidates often continue using useEffect for mutations instead of embracing Action-driven flows.
Can React 19 reduce the need for external state management libraries?
Yes, for many applications. With Actions, useOptimistic, and Server Components, React 19 can handle common async and shared state patterns that previously required Redux or similar libraries. However, complex global state may still benefit from dedicated solutions.
Why Interviewers Ask This
Interviewers want to see balanced judgment rather than extreme opinions.
Common Mistakes
Claiming Redux is obsolete without understanding trade-offs is a common red flag.
What kind of applications benefit the most from React 19?
Applications with heavy async interactions, form-driven workflows, and server-rendered content benefit most. React 19 is particularly powerful for modern SaaS dashboards, content platforms, and data-intensive applications.
Why Interviewers Ask This
This question tests the ability to apply technology choices to real-world scenarios.
Common Mistakes
Candidates often answer generically without mapping features to actual use cases.
This React.js interview question and answer guide is designed to help developers at all levels—from beginners to advanced engineers—strengthen their understanding of React concepts and prepare for technical interviews. By studying topics such as components, props, state management, hooks, routing, Redux, performance optimization, and advanced patterns, you can gain confidence in real-world scenarios and showcase your React expertise during interviews. Keep practicing, experiment with the code examples provided, and continually explore modern React best practices to stay ahead in your career.
Disclaimer: The content on this page is for educational and preparatory purposes only. While we strive to provide accurate and up-to-date information, interview questions and company-specific requirements may vary. PrepForHire does not guarantee any specific outcomes in interviews or job applications. Always supplement this material with hands-on coding experience and official documentation.