Top 150+ React Interview Questions You Must Prepare (With Answers)
React Coding Interviews are notoriously unpredictable. One interviewer might drill into hooks and state management, while another dives deep into Redux, performance optimization, or TypeScript integration. The challenge isn’t just knowing React, it’s knowing which questions are most likely to come up and how to answer them with clarity. With 150+ React interview questions and answers, it brings together the most frequently asked and trickiest topics, from JSX, virtual DOM, and lifecycle methods to advanced hooks, context API, routing, testing, and best practices.
To help with that, Interview Coder offers an undetectable coding assistant for interviews that gives realistic practice questions, clear answers, and live feedback. Hence, you build skills and remain calm under pressure. It simulates real interview pacing, highlights weak spots in your code, and helps you turn study time into steady progress.
Top 70 React Interview Questions and Answers For Freshers

1. What is ReactJS?
ReactJS is a JavaScript library for building the view layer of web apps using reusable components. It shines for single-page applications because components, the Virtual DOM, and efficient re-rendering let the UI update without full page reloads.
JSX is commonly used to write React components. Key features include the Virtual DOM, component-based design, Hooks to use state and effects in functions, server-side rendering for faster initial loads and SEO, and routing via libraries such as React Router.
2. What Is the Latest Version of React?
The latest stable React release is v19.1.0, published March 28, 2025. It builds on the major changes introduced in v19.0.0 from December 5, 2024.
3. Explain the MVC Architecture
Model-View-Controller splits an app into three parts:
- Model holds data and business rules
- View renders the UI
- Controller handles input and updates the model or view
4. Explain the Building Blocks of React
React’s main parts:
- Components: Reusable UI units that return JSX.
- JSX: JavaScript syntax extension that looks like HTML.
- Props and State: Props pass data in; state stores local, changeable data.
- Context: Share data across many components without prop drilling.
- Virtual DOM: An in-memory copy of the DOM used to compute minimal updates.
5. Explain Props and State in React with Differences
Props pass data into a component from its parent and are read-only. State lives inside a component and can change over time. Quick differences:
- Props: Passed from parent, immutable, used in both function and class components.
- State: Local to component, mutable via setState or useState, mostly managed inside the component.
6. What is Virtual DOM in React?
The Virtual DOM is an in-memory representation of the real DOM. React builds a new virtual tree on updates, diffs it against the previous tree, and applies the minimal set of real DOM changes. That diffing and batching make updates faster.
7. Differentiate Between Real DOM and Virtual DOM?
Real DOM:
- Actual browser DOM tree
- Slower for many updates
- Direct updates can re-render large parts of the UI
Virtual DOM:
- Lightweight copy kept in memory
- Faster because React computes minimal changes
- Batches and applies only necessary updates to the real DOM
8. What is JSX?
JSX is a JavaScript syntax extension that looks like HTML and lets you create React elements in a readable way. Use curly braces {} to embed JavaScript expressions inside JSX.
Example:
const name = "Learner";const element = ( <h1> Hello, {name}. Welcome to GeeksforGeeks. </h1>);
9. What are Components and Their Type in React?
A component is a reusable piece of UI. Two main types:
- Functional components: Plain functions that return JSX; with Hooks they can hold state and use lifecycle-like effects.
- Class components: ES6 classes that extend React.Component; they use this.state and lifecycle methods. Hooks have reduced the need for classes.
10. How Do Browsers Read JSX?
Browsers cannot run JSX directly. A transpiler such as Babel converts JSX into plain JavaScript before the code runs in the browser.
11. Explain the Steps to Create a React Application and Print Hello World
Install Node, then create an app with Vite:npm create vite@latestcd <Application_Name>Example App component:import React from "react";import "./App.css";function App() { return <div className="App">Hello World !</div>;}export default App;Run the app with:npm start
12. How to Create an Event in React?
Attach event handlers like onClick or onChange to JSX elements and define the handler function.
Example:
function Component() { const doSomething = (e) => { e.preventDefault(); // response to the event }; return <button onClick={doSomething}>Click</button>;}
13. Explain the creation of a List in React?
Use Array.map to transform values into elements and give each item a unique key.
Example:
import React from "react";import ReactDOM from "react-dom/client";const numbers = [1, 2, 3, 4, 5];const updatedNums = numbers.map(number => <li key={number}>{number}</li>);const root = ReactDOM.createRoot(document.getElementById("root"));root.render(<ul>{updatedNums}</ul>);
14. What is a Key in React?
A key is a special attribute used on list elements so React can track which items change, get added, or are removed. Use stable, unique values as keys.
15. How to Write a Comment in React?
In JavaScript and JSX:
- Single line: // This is a single-line comment
- Multi-line: /* This is a multi-line comment */
16. Explain the Difference Between React and Angular
React:
- A JavaScript library focused on UI
- Uses Virtual DOM and one-way data flow
- Simpler core and very modular
Angular:
- A full framework
- Uses real DOM and two-way data binding
- Provides an opinionated architecture and more built-in features
17. Explain the Use of the Render Method in React?
In class components, render() returns the JSX to display. React calls render to convert component state and props into virtual nodes that become real DOM.
18. What is State in React?
State is an object that holds data affecting how a component renders and behaves. Updating state causes React to re-render the component.
19. Explain Props in React?
Props are objects passed from parent to child components. Access them with this.props in class components, or as function arguments in functional components.
20. What is Higher-Order Component in React?
A higher-order component is a function that takes a component and returns a new enhanced component. HOCs let you share common functionality without repeating code.
21. Explain the Difference Between Functional and Class Component in React?
Functional Components:
- Simple JS functions taking props
- Use Hooks for state and effects
- No render method
Class Components:
- Extend React.Component and must implement render()
- Use this.state and lifecycle methods
- Require constructor when initializing state
22. Explain One Way Data Binding in React?
React uses one-way data flow: data travels from parent to child via props. Children do not directly modify parent props, which makes behavior easier to reason about.
23. What is Context API in React?
Context API lets you provide a value at a high level and consume it in nested components without passing props through each level. Use a Provider to set the value and useContext or Consumer to read it.
24. What is the Role of shouldComponentUpdate() in React?
shouldComponentUpdate(nextProps, nextState) returns true or false to tell React whether to re-render the component when props or state change. Returning false skips the update and saves work.
25. What is the Use of dangerouslySetInnerHTML in React?
dangerouslySetInnerHTML lets you set raw HTML inside a component. It bypasses React’s escaping, so use it only for trusted content because it can expose the app to XSS attacks.
26. What are Pure Components in React?
React.PureComponent implements a shallow prop and state comparison to avoid unnecessary re-renders. Use it when shallow checks are sufficient to detect changes.
27. What is the significance of setState() in React?
setState() schedules an update to a component’s state. After state changes, React re-renders the component and its children to reflect the new data.
28. What is Conditional Rendering in React?
Conditional rendering displays different components depending on conditions. For example:{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
29. What is React Router?
React Router is a library for routing in React applications. It manages navigation, updates the URL, and keeps the UI in sync with route changes. Install with:npm i react-router-dom
30. Explain the components of a React-Router
Main parts:
- BrowserRouter (Router): Wraps the app and enables routing.
- Switch: Renders only the first matching Route (in older versions).
- Route: Renders a component when the path matches.
- Link: Navigates without a full page reload.
31. How Is React Routing Different from Conventional Routing?
React routing runs in the browser for single-page apps and avoids full-page reloads. Conventional routing usually requests new HTML from the server for each navigation and triggers full page reloads.
32. Explain the Lifecycle Methods of Components
A component passes through:
- Initialization: Constructor sets initial props and state.
- Mounting: Component is added to the DOM and rendered.
- Updating: State or props change and component re-renders.
- Unmounting: Component is removed from the DOM.
33. Explain the Methods Used in Mounting Phase of Components
Mounting methods include:
- componentWillMount(): invoked before mounting (legacy and not recommended).
- componentDidMount(): invoked after the component mounts and the initial render completes.
34. What is this.setState Function in React?
this.setState updates the component state and triggers re-rendering. You can update only parts of the state and call setState multiple times; React batches updates for performance.
35. What is the Use of Ref in React?
Refs let you access DOM nodes or component instances directly when needed, for example to manage focus or play a video. Use this.myRef.current in class components or useRef in functions.
36. What are Hooks in React?
Hooks let function components use state, refs, context, and lifecycle-like behavior. They include built-in hooks such as useState, useEffect, useRef, and let you create custom hooks.
37. Explain the useState Hook in React?
useState declares state inside a function component:const [state, setState] = useState(initialState);state holds the current value; setState updates it and triggers re-render.
38. Explain the useEffect Hook in React?
useEffect(function, dependencies) runs side effects like data fetching or subscriptions. The dependencies array controls when the effect re-runs. It replaces lifecycle patterns like componentDidUpdate and componentWillUnmount in many cases.
39. What are React Fragments?
React.Fragment or <> </> wraps multiple elements without adding an extra div to the DOM.Example:<React.Fragment> <h2>Child-1</h2> <p>Child-2</p></React.Fragment>
40. What is a React Developer Tool?
React Developer Tools is a browser extension that adds an inspector for React components. You can browse the component tree and inspect props, state, and hooks.
41. How to Use Styles in ReactJS?
CSS Modules scope styles locally. Name the file App.module.css and import it:import styles from './App.module.css';Then use styles.className on elements.
42. Explain Styled Components in React?
Styled-components lets you write component-scoped CSS inside JavaScript. Install:npm i styled-components
Example:
import styled from 'styled-components';const Button = styled.div` width: 100px; cursor: pointer; text-decoration: none;`;export default Button;
43. What is Prop Drilling and Its Disadvantages?
Prop drilling happens when you pass props through intermediate components that do not need the data, just to reach a deeply nested one. It creates cluttered code and makes maintenance harder.
44. What is Conditional Rendering in React?
Conditional rendering switches UI based on a condition.
Example:
const isLoggedIn = true;return ( <div> {isLoggedIn ? <button>Logout</button> : <button>Login</button>} </div>);
45. What are Controlled Components in React?
Controlled components use React state as the single source of truth for form inputs. Input values come from the state and are updated via onChange handlers.
46. What is CustomHooks in React?
Custom hooks are functions starting with use that call built-in hooks. They encapsulate reusable logic so you can share behavior across components without repeating code.
47. How to Optimize a React code?
Optimize by:
- Binding functions in constructors where needed.
- Avoid inline props or handlers that change on each render.
- Using React.Fragment to avoid extra DOM nodes.
- Lazy loading components to reduce initial bundle size.
48. What is the Difference Between useRef and createRef in React?
useRef
- Hook used in function components
- Keeps the same ref across re-renders
- Returns a mutable object.
createRef:
- Function often used in class components
- Creates a new ref each render if used in functions
- Typical usage in class component constructors
Examples:
- const myRef = useRef();
- const myRef = React.createRef();
49. What is React-Redux?
React-Redux connects Redux state management to React components. It simplifies sharing state across many components without passing props down many levels.
50. What are the Benefits of Using React-Redux?
Benefits:
- Centralized single store for application state.
- Improved performance by reducing unnecessary re-renders.
- Easier debugging with predictable state changes.
- Persistent state handling for longer-lived data.
51. Explain the Core Components of React-Redux?
Core Redux concepts:
- Store: Holds the entire app state.
- Actions: Plain objects describing state changes.
- Action creators: Functions that return actions.
- Reducers: Pure functions that update state based on actions.
52. How Can We Combine Multiple Reducers in React?
Use combineReducers to merge reducers into one root reducer.
Example:
import { combineReducers } from "redux";const rootReducer = combineReducers({ books: BooksReducer, activeBook: ActiveBook});
53. Explain CORS in React?
Cross-Origin Resource Sharing allows the browser to request resources from a different domain. When frontend and backend run on different domains, configure the server and use libraries like axios or fetch on the client to handle cross-origin requests.
54. What is Axios, and How to Use it in React?
Axios is a popular library for making HTTP requests and handling CRUD operations. It supports Promises and works well in React for API calls. Install with:npm i axios
55. Write a Program to Create a Counter with Increment and Decrement
Example component using useState:import React, { useState } from "react";const App = () => { const [counter, setCounter] = useState(0); const handleClick1 = () => setCounter(counter + 1); const handleClick2 = () => setCounter(counter - 1); return ( <div> <div>{counter}</div> <div className="buttons"> <button onClick={handleClick1}>Increment</button> <button onClick={handleClick2}>Decrement</button> </div> </div> );};export default App;
56. Explain Why and How to Update State of Components Using Callback?
Using a callback version of setState ensures you update state based on the latest value, preventing bugs when updates queue up.Example:this.setState(prevState => ({ count: prevState.count + 1}));
57. What is React-Material UI?
Material UI is an open-source UI component library for React that implements Material Design. It provides styled, accessible components and speeds up building consistent interfaces.
58. What is Flux Architecture in Redux?
Flux is a pattern with unidirectional data flow: actions dispatch to a store, the store updates state, and the view reacts. Redux follows this approach to make the state predictable and traceable.
59. What are Custom Hooks in React?
Custom hooks are user-defined functions that call built-in hooks to encapsulate and reuse stateful logic across components. Name them starting with use.
60. How Can You Optimize React Performance?
Use React.memo to skip re-renders, React.lazy and Suspense for code splitting, useMemo and useCallback to memoize values and functions, and avoid unnecessary state updates.
61. What is the Strict Mode in React?
React.StrictMode is a development tool that highlights potential problems. Wrap the app or parts of it with <React.StrictMode> to enable extra checks without affecting production behavior.
Example:
import React from "react";import ReactDOM from "react-dom";const App = () => <div><h1>Hello, World!</h1></div>;ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root"));
62. What is Redux, and How Does It Work with React?
Redux stores global state in a single store and updates it via actions processed by reducers. React-Redux connects that store to React components so they can read state and dispatch actions.
63. How does React Handle Concurrency?
React’s concurrency features let React split rendering work, pause it, and prioritize urgent updates. This helps apps stay responsive under heavy work by scheduling lower-priority tasks later.
64. How does React Handle Server-Side Rendering (SSR)?
Server-side rendering runs React on the server to produce HTML that the client can display immediately. That approach speeds the first paint and improves SEO since crawlers see fully rendered HTML.
65. What are Forms in React?
Forms in React are elements like input, select, and textarea. You can use controlled components, where React state holds input values, or uncontrolled components, which use refs to read values.
66. How to Create Forms in React?
Steps:
- Create a state with useState for each input
- Bind input value to state
- Update state in onChange handlers
- Handle submission in onSubmit and prevent default behavior
Example:
import React, { useState } from 'react';function MyForm() { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = (e) => { e.preventDefault(); console.log('Form submitted:', { name, email, message }); }; return ( <form onSubmit={handleSubmit}> <div> <label>Name:</label> <input type="text" value={name} onChange={e => setName(e.target.value)} /> </div> <div> <label>Email:</label> <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> </div> <div> <label>Message:</label> <textarea value={message} onChange={e => setMessage(e.target.value)} /> </div> <button type="submit">Submit</button> </form> );}export default MyForm;
67. What is Lazy Loading in React?
Lazy loading delays loading a component until it is required. React.lazy and Suspense let you split code and reduce initial bundle size, improving load performance.
68. How is React Different from React Native?
React:
- Library for building web UIs using HTML, CSS, and JavaScript
React Native:
- Framework for building native mobile apps using React principles and native UI components like View and Text
69. What is Memoization in React?
Memoization stores the result of expensive computations and returns the cached result when inputs stay the same. React tools:
- React.memo for functional component memoization.
- useMemo to memoize computed values.
70. What is Reconciliation in React?
Reconciliation is React’s process for updating the DOM when state or props change. React diffs the old and new Virtual DOM trees, computes the minimal updates, and applies them to the real DOM. The Fiber algorithm lets React pause and prioritize parts of this work so complex apps remain responsive.
Related Reading
- Vibe Coding
- Leetcode 75
- Jenkins Interview Questions
- React Interview Questions
- Leetcode Patterns
- Java Interview Questions And Answers
- Kubernetes Interview Questions
- Azure Interview Questions
- Angular Interview Questions
- SQL Server Interview Questions
- Leetcode Blind 75
- C# Interview Questions
- AngularJS Interview Questions
- TypeScript Interview Questions
- AWS Interview Questions
20 More React Interview Questions and Answers For Freshers

71. useState explained: Local State Inside Functional Components
useState is a built-in React Hook that gives functional components local state. Call it at the top level of a component. It returns a pair: the current value and a setter function you call to update that value. The setter triggers a re-render of the component.
Example:
const [count, setCount] = useState(0);function increment() { setCount(prev => prev + 1);}
Notes and practical tips:
- Always treat the state as immutable. Use the setter with a new value or an updater function that receives the previous state.
- Use separate state variables for unrelated pieces of data to keep updates focused and predictable.
- Calling the setter is asynchronous. If you need the previous value, use the updater form: setCount(c => c + 1).
- Keep heavy computed values outside the state. UseMemo or compute on render when cheap.
72. Keys in Lists: Why Unique IDs Matter and How to Use Them
Keys are a special prop React uses to identify list items across renders. They let React match previous and next elements so it can update only what changed.
Best practices:
- Use stable, unique IDs from your data, not array indexes, when items can be reordered or inserted.
- Keys must be unique among siblings only.
- Avoid using random values or timestamps as keys; that forces unmount and remount, and kills performance.
- Use keys to optimize dynamic lists and preserve component state within list items.
73. JSX: What It Is and Why We Write It
JSX lets you write HTML-like syntax inside JavaScript. It is syntactic sugar for React.createElement calls. Browsers do not understand JSX directly, so build tools transpile it to plain JavaScript.
Example:
const el = <div><p>Hello</p></div>;transpiles roughly toReact.createElement('div', null, React.createElement('p', null, 'Hello'));
Notes:
- JSX can embed expressions with {}.
- Use className instead of class and htmlFor instead of for.
- You can write React without JSX, but JSX stays more concise and readable for component markup.
74. Virtual DOM: How React Batches Updates and Minimizes DOM Work
Virtual DOM is an in-memory representation of UI elements. React updates the virtual DOM first, diffs it against the previous version, then applies the minimal set of fundamental DOM changes. This reduces costly DOM operations.
How it helps:
- React compares virtual DOM trees and calculates the least work to update the real DOM.
- Keys help the diffing algorithm identify moved or removed items.
- React also batches state updates inside events for efficiency.
75. Controlled vs Uncontrolled Components: Forms and When to Pick Which
Controlled components keep form input values in React state and update via onChange. Uncontrolled components let the browser manage input state and use refs to read values when needed.
Controlled example:
<input value={value} onChange={e => setValue(e.target.value)} />
Uncontrolled example:
const ref = useRef();<input defaultValue="hi" ref={ref} />on submit read ref.current.value
When to use each:
- Use controlled inputs for validation, conditional disabling, complex interdependent fields, dynamic inputs, and when you need to enforce format.
- Use uncontrolled when integrating with non-React code, for simple forms where you only need a value on submit, or for file inputs where controlled handling is awkward.Performance and gotchas
- Controlled inputs cause re-renders on every change. If you have many inputs and observe performance issues, batch updates, or use uncontrolled components selectively.
- Use defaultValue for uncontrolled inputs and value for controlled ones.
- For dynamic lists of inputs, controlled components scale better for validation and aggregated state handling.
Tooling:
- For complex forms, prefer form libraries such as React Hook Form or Formik. They manage performance, validation, and nested fields while allowing either controlled or uncontrolled patterns.
76. Props: Data In, One-Way Flow
Props are read-only inputs passed from parent to child. They let you parameterize components and compose UI. A child must not modify its props directly. Pass callbacks if a child needs to request changes to the parent state.
Example:
<Profile name="Ava" onChange={newName => setName(newName)} />Tips:
- Use prop types or TypeScript to document and validate prop shapes.
- Prefer passing minimal necessary data and callbacks to avoid excessive prop drilling.
77. State Versus Props: Who Owns What and Where to Lift State
Props are inputs from parent components and are read-only. State is owned by the component that defines it and is mutable via setState or Hook setters.
When to lift the state up:
- If two sibling components need the same piece of data, move that state to their closest common parent and pass it down as props.
- Keep the state as local as possible. Lift it only when multiple components must share it.
Patterns:
- For derived values, compute them during render instead of duplicating state.
- For many related form fields, keep a single object state or use a form library.
- Use callbacks passed through props to allow children to request updates.
78. Types of Side Effects in Components and How to Manage Cleanup
Side effects include network requests, subscriptions, manual DOM mutations, timers, and logging. Some effects need cleanup to avoid leaks or duplicate work.Two categories:
- Effects without cleanup: simple requests, logging, and non-persistent actions.
- Effects with cleanup: subscriptions, timers, and manually attached event listeners. Return a cleanup function from useEffect to remove subscriptions or clear timers.
Example:
useEffect(() => { const id = setInterval(tick, 1000); return () => clearInterval(id);}, []);
Rules:
- Keep effect dependencies precise to avoid unnecessary re-runs.
- Clean up resources to prevent memory leaks and duplicate listeners.
79. Prop Drilling: Why It Happens and How to Avoid It
Prop drilling is passing props down through intermediate components that do not use them, just to reach a deeply nested child. It creates tight coupling and noisy component signatures.
Alternatives:
- Lift state to a common ancestor and pass only what is needed.
- Use Context for app-wide or cross-subtree data like theme or auth.
- Use composition patterns or custom hooks to expose behavior without deep prop chains.
Practical rule:
- Use Context when many components across the tree need the same value and prop passing becomes repetitive.
80. Error Boundaries: Catching Render-Time Failures and Reporting
Error boundaries are class components that implement static getDerivedStateFromError and componentDidCatch to catch errors during render, lifecycle, or constructors of child components. They let you show a fallback UI instead of unmounting the entire app.
Example:
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } componentDidCatch(error, info) { logError(error, info); } render() { if (this.state.hasError) return <div>Something went wrong</div>; return this.props.children; }}
Limitations and best practices:
- Error boundaries do not catch errors inside event handlers, async callbacks, server-side code or errors thrown in the boundary itself.
- Place boundaries around risky parts such as third-party widgets, routes, or heavy components.
- Provide a mechanism to reset the boundary state after an error, for example a try again button that changes a key prop or updates state.
81. React Hooks Overview: Moving State and Lifecycle Into Functions
Hooks are functions like useState and useEffect that let you manage state and side effects in functional components. They let you reuse logic via custom hooks and reduce the need for class components.
Key points:
- Hooks must be called at the top level of a function component or inside custom hooks.
- They let you compose behavior across components without changing component hierarchy.
82. Explain Hooks: Common Ones and How to Use Them Correctly
- useState: local state.
- useEffect: side effects and cleanup.
- useRef: mutable refs that persist across renders for DOM nodes or mutable variables.
- useMemo: memoize expensive calculations.
- useCallback: memoize function references to avoid unnecessary child re-renders.
Practical tips:
- Keep effect dependencies explicit and minimal to avoid stale closures.
- Prefer useRef for mutable values you need to persist without triggering renders.
83. Rules of Hooks: How to Avoid Subtle Bugs
- Call Hooks only at the top level of your component. Do not call them inside loops, conditions, or nested functions.
- Call Hooks only from React function components or custom hooks.
Why these rules matter:
- They keep the Hook call order stable so React can correctly associate state and effects with a component instance.
84. useEffect explained: Running Effects and Dependency Control
useEffect runs after render for side effects like data fetching or document updates. It accepts a function and an optional dependencies array. If you pass dependencies, React runs the effect only when any dependency changes. If you return a function from the effect, React runs that as cleanup before the next effect or unmount.
Example:
useEffect(() => { fetchData(); return () => cancelFetch();}, [userId]);
Best practices:
- Keep effects focused on a single job.
- Avoid recreating functions inside dependencies unless needed.
- Use abort controllers for fetches to cancel stale requests.
84. useRef and refs in Hooks: When to Use Them
useRef returns a mutable ref object that survives renders. Use it to access DOM nodes, store timers, or keep mutable values without triggering re-renders.
Examples:
- Managing focus: inputRef.current.focus()
- Storing previous props: prevRef.current = currentValue
- Integrating non-React libraries that require DOM elements
85. Custom Hooks: Reusable Logic With a Simple Rule
Custom Hooks are functions whose names start with use and that call other Hooks. They package reusable behavior like data fetching, form state, or subscriptions and return values or callbacks to the component.
Example:
function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { fetch(url).then(r => r.json()).then(setData); }, [url]); return data;}
Rules:
- Follow Hook rules when writing custom hooks.
- Do not use them inside class components.
86. Keys Revisited: More Examples and Anti-Patterns
Keys improve reconciliation by giving elements stable identities. Use keys to preserve component instances across reorder. Avoid these anti-patterns:
- Using an array index as a key when the list order changes.
- Generate new keys every render.
- Using keys to force remounts unless you purposely need fresh component state.
When forcing remount is valid:
- Remounting can be useful to reset a component when an ID changes, for example, <Form key={userId} />, which creates a fresh form instance.
87. Why JSX Needs Transpilation and Build Tools
JSX looks like HTML inside JavaScript, but browsers only understand plain JavaScript. Tools such as Babel convert JSX into React.createElement calls so the browser can execute it. Build tools also enable modern syntax and optimize output.
88. Styling React Components: Options and Trade-Offs
Header: CSS strategies for React projects and when to use them:
- Global CSS files: simple and familiar. Good for static styles.
- Inline styles: scoped to an element, but lack pseudo-selectors and media queries.
- CSS Modules: local scope and predictable class names.
- CSS in JS libraries: styled components and emotion let styles react to props and scope automatically.
Choose based on team conventions, performance needs, and how dynamic your styles must be.
89. StrictMode: Why Run Extra Checks in Development
StrictMode is a development-only wrapper that runs additional checks, such as double-inverting certain functions to find impure renders and missing effect cleanups. Enable it at the app root or per subtree to surface issues while developing.
90. Graceful Error Handling: Practical Approaches for Robust Apps
Wrap risky components with error boundaries to catch render time errors and display fallback UI. For production-grade error handling:
- Log errors to a tracking service in componentDidCatch.
- Provide a recovery path, such as a retry button that resets boundary state or a navigation option to another route.
- Combine error boundaries with route-level boundaries in router setups to keep failures isolated to single pages.
20 React Interview Questions for the Experienced

1. Smooth Post‑Login Redirect — Automatic Navigation After Authentication
Render a redirect from your router when authentication completes, or navigate programmatically. In react‑router v5 you can use <Redirect>, and in v6 use the useNavigate hook. Preserve the intended destination in state to return users to where they started, and validate any returnTo value to avoid open redirect attacks.
Example v5 (conditional render):
class Login extends React.Component { state = { loggedIn: false }; render() { if (this.state.loggedIn) { return <Redirect to="/dashboard" />; } return <form>{/* login form */}</form>; }}
Example v6 (programmatic):
import { useNavigate, useLocation } from 'react-router-dom';function Login() { const navigate = useNavigate(); const location = useLocation(); const from = (location.state && location.state.from) || '/'; async function onSuccess() { // set token etc navigate(from, { replace: true }); // replace prevents back to login } return <form onSubmit={submit}>...</form>;}
Best practices:
- Use replace for the final redirect to avoid leaving login in history.
- Store the intended path in location.state or a safe cookie.
- Validate returnTo against an allowlist to prevent open redirects.
- For SSR, perform redirect on the server by returning a 302 or by hydrating to the right route.
2. Sibling Data Passing with React Router — URL Params, Location State, or Shared Store
You can send data between sibling routes with URL params, query strings, or history state. For short, navigational data, use match.params or location.state. For complex shared state, use Context or a global store.
URL param:
- props.history.push(`/about/${id}`);
Location state:
- history.push('/about', { item });
Receiving side:
- const location = useLocation();const item = location.state?.item;
When to choose what:
- URL params: good for bookmarking and deep linking.
- location.state: transient, not bookmarked, avoids polluting URL.
- Context or Redux: use for larger or persistent shared state across many routes.
3. Re-render on Resize — Responsive Reactivity Without Waste
Create a reusable hook that listens to window resize, throttles updates, and cleans up on unmount. Debounce with requestAnimationFrame or a small throttle to avoid many renders.
Example hook:
import { useState, useEffect } from 'react';function useWindowSize() { const [size, setSize] = useState({ w: 0, h: 0 }); useEffect(() => { function onResize() { setSize({ w: window.innerWidth, h: window.innerHeight }); } onResize(); let raf = null; function handler() { if (raf) cancelAnimationFrame(raf); raf = requestAnimationFrame(onResize); } window.addEventListener('resize', handler); return () => { window.removeEventListener('resize', handler); if (raf) cancelAnimationFrame(raf); }; }, []); return size;}
Notes:
- Guard for SSR where window is undefined.
- Throttle or debounce to reduce rerenders on continuous resize.
4. Build a Page Switcher — Mapping Props to Components Cleanly
Implement a switcher via a mapping object, dynamic import for code splitting, and type checks for safety. Use lazy and Suspense if pages are large.
Basic pattern:
const PAGES = { home: Home, about: About, contact: Contact };function Page({ page, ...props }) { const Comp = PAGES[page] || NotFound; return <Comp {...props} />;}
Code-split version:
const Home = React.lazy(() => import('./Home'));return ( <Suspense fallback={<Spinner />}> <Page page={page} /> </Suspense>);
Best practices:
- Validate page prop with PropTypes or TypeScript union types.
- Favor route-driven switching (react-router) for navigable pages.
- Keep the page registry centralized for analytics and permissions.
5. Simple React Hooks Example — State, Effect, and a Controlled Input
A compact, interview‑friendly example shows useState and useEffect and demonstrates lifecycle equivalence.
Example:
import { useState, useEffect } from 'react';function SearchList({ items }) { const [query, setQuery] = useState(''); const [results, setResults] = useState(items); useEffect(() => { setResults(items.filter(i => i.name.includes(query))); }, [query, items]); return ( <div> <input value={query} onChange={e => setQuery(e.target.value)} /> <ul>{results.map(r => <li key={r.id}>{r.name}</li>)}</ul> </div> );}
Tips for interviews:
- Explain how useEffect combines mount/update/unmount logic.
- Show how to extract behavior into custom hooks for reuse.
6. Conditional Rendering — Patterns That Scale and Stay Readable
Common techniques:
- if/return early: ideal for guarding large sections.
- ternary: concise for inline choices.
- && short circuit: show-only-if truthy cases.
- component guards: wrap logic in small components (e.g., <AuthGuard>).
- switch or map for many cases: map a status to a component.
Example using guard:
if (!user) return <LoginPrompt />;return <Dashboard />;
Avoid:
- Deeply nested ternaries. Use small components to keep the render readable.
7. Can Hooks Replace Redux — When to Use Local Reducers vs. a Full Store
Hooks enable local reducer patterns (useReducer) and shared state via Context. For small to medium apps, useReducer + Context or libraries like Zustand can be simpler than Redux.
Tradeoffs:
- Use hooks + context when the state is localized or only a few components consume it.
- Use Redux (or RTK) when you need time travel, complex middleware, predictable devtools, or a large normalized state with many consumers.
- For performance-sensitive apps, normalize state and use selectors (reselect) to avoid prop churn.
Hybrid approaches:
- Keep UI state in hooks and complex domain state in Redux.
- Use Redux Toolkit to reduce boilerplate if choosing Redux.
8. React Router Essentials — Modern Routing and Hooks
React Router provides client routing with sync to URL. v6 simplified route structure and introduced hooks like useNavigate, useParams, useLocation, and useRoutes for nested routing.
Key points:
- Use nested routes to match component hierarchy.
- Prefer hooks over HOCs; they return simple primitives for navigation and params.
- For SSR, render routes on the server and handle redirects by checking matched routes during render.
Example:
import { Routes, Route } from 'react-router-dom';<Routes> <Route path="/" element={<Home/>}/> <Route path="users/:id" element={<User/>}/></Routes>
9. Do Hooks Cover Class Functionality — Mapping and Exceptions
Hooks cover mount/update/unmount flows via useEffect and support state via useState and useReducer. Some class features remain class-only today:
Limitations:
- Error boundaries still require class components (componentDidCatch) until APIs expand.
- Certain lifecycle control patterns map awkwardly but usually have hook equivalents.
Pattern guidance:
- Use useEffect cleanup for unmount logic.
- Combine hooks or create custom hooks to model complex lifecycle sequences.
10. Hooks vs Classes Performance — Tradeoffs and Common Pitfalls
Hooks remove instance allocation and binding overhead present in classes and enable flatter component composition. But closures create different performance considerations.Performance notes:
- Hooks let you avoid wrapper components like some HOCs, reducing tree depth.
- Beware creating new functions/objects inline; they break referential equality and trigger child updates unless memoized.
- Profile with React DevTools profiler and Chrome to identify hotspots.
Optimization tactics:
- Use React.memo, useCallback, and useMemo judiciously.
- Prefer immutable updates to make shallow comparisons effective.
11. Hooks Compared to Classes — Practical Differences
- Syntax: hooks use functions; classes use class syntax and this.
- State setup: useState and useReducer vs this.state and setState.
- Lifecycle: useEffect vs lifecycle methods.
- Reuse: custom hooks replace many HOC and render-prop patterns.
- Instances: functions avoid instance creation but can introduce closure traps.
12. Hook Types and Patterns — Built-In and Custom Hooks That Matter
Built-ins:
- Basic: useState, useEffect, useContext.
- Additional: useReducer, useMemo, useCallback, useRef, useLayoutEffect, useImperativeHandle, useDebugValue.
Custom hooks:
- Encapsulate reusable behavior (fetching, input handling, subscriptions).
- Name must start with use.
- Follow the Rules of Hooks: call unconditionally and only from components or other hooks.
Example custom hook:
function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { let cancelled = false; fetch(url).then(r => r.json()).then(d => { if (!cancelled) setData(d); }); return () => { cancelled = true; }; }, [url]); return data;}
13. Static Typing with Hooks — TypeScript Patterns and Examples
Hooks work well with TypeScript. Type component props, state generics, dispatch signatures, and refs.
Examples:
const [count, setCount] = useState<number>(0);type Action = { type: 'inc' } | { type: 'dec' };const [state, dispatch] = useReducer((s: number, a: Action) => ..., 0);
Typing refs:
const inputRef = useRef<HTMLInputElement | null>(null);
14. Lifecycle Methods — Class Methods and Hook Equivalents
Class methods:
- constructor
- getDerivedStateFromProps
- render
- componentDidMount
- shouldComponentUpdate
- getSnapshotBeforeUpdate
- componentDidUpdate
- componentWillUnmount
Hook mappings:
- Mount/update/unmount: useEffect
- Synchronous DOM reads: useLayoutEffect.
- Avoid getSnapshotBeforeUpdate by capturing values in refs before update.
15. Component Lifecycle Phases — Initialization to Unmount
Phases:
- Initialization: set initial state and props.
- Mounting: component enters DOM; use componentDidMount or useEffect with empty deps.
- Updating: triggered by props or state changes; use componentDidUpdate or useEffect with deps.
- Unmounting: cleanup subscriptions with componentWillUnmount or effect return.
16. Higher‑Order Components — When and How to Abstract Behavior
HOC = function that takes a component and returns a new component. Use HOCs to share behavior like subscriptions, data sources, or feature toggles.
Example HOC:
function withData(Wrapped, select) { return class extends React.Component { state = { data: select(DataSource) }; componentDidMount() { DataSource.subscribe(this.update); } componentWillUnmount() { DataSource.unsubscribe(this.update); } update = () => this.setState({ data: select(DataSource) }); render() { return <Wrapped {...this.props} data={this.state.data} />; } };}
Pitfalls and alternatives:
- HOCs can obscure props and refs; use forwardRef where needed.
- Consider hooks and composition as simpler alternatives for new code.
- Preserve displayName and static methods when wrapping.
17. Passing Data Between Components — Patterns From Props to Context
- Parent to child: props.
- Child to parent: callbacks passed via props.
- Siblings: lift state to common parent, use Context, or route state.
- Global: Redux, Zustand, or Context for broadly shared state.
Example child-to-parent:
function Parent() { const [value, setValue] = useState(0); return <Child onChange={setValue} value={value} />;}function Child({ value, onChange }) { return <button onClick={() => onChange(value + 1)}>Inc</button>;}
18. Performance Optimization Techniques — Practical Checklist
- Memoize heavy computations with useMemo.
- Memoize handlers with useCallback to avoid child re-renders.
- Wrap pure components with React.memo or use PureComponent.
- Window large lists with react-window or react-virtualized.
- Lazy load routes and components with React.lazy and Suspense.
- Split bundles with dynamic imports and analyze bundles with source-map-explorer.
- Avoid unnecessary object/array allocations in render.
- Debounce user input and expensive updates.
- Use web workers for CPU work and server‑side rendering for initial load.
19. Styling React Components — Options and When to Pick Them
Common choices:
- CSS files and modules: predictable, caches well, CSS module scoping.
- CSS-in-JS: styled-components, emotion — dynamic styles and theming.
- Utility frameworks: Tailwind for rapid layout and low runtime CSS.
- Inline styles for simple dynamic rules or critical styling.
- Classnames library for conditional classes.
Selection guide:
- Choose CSS modules or plain CSS for performance-critical sites.
- Use CSS-in-JS when you need JS-driven theming or component-scoped styles.
- Keep class naming predictable and document style decisions.
20. Preventing Unnecessary Re-renders — Patterns and Examples
Tools:
- shouldComponentUpdate in classes or React.PureComponent.
- React.memo for function components.
- useMemo and useCallback to stabilize references.
- Keep state local where possible and split components so only the necessary bits update.
Example:
const Message = React.memo(function Message({ text }) { return <p>{text}</p>;});
Avoid passing fresh objects:
return <Child options={{ a: 1 }} />; // creates new object each render
Instead:
const opts = useMemo(() => ({ a: 1 }), []);return <Child options={opts} />;
21. Strict Mode — Development Checks That Catch Risky Patterns
React.StrictMode runs extra checks in development: double invokes certain functions to reveal unsafe side effects, warns about deprecated lifecycle use, flags legacy string refs and findDOMNode usage, and highlights legacy context. Wrap parts of your app to get these diagnostics.
Usage: ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, root);
Practical notes:
- StrictMode only affects development and can surface cleanup issues early.
- Expect effects to run twice in development under StrictMode; use idempotent effects and proper cleanup.
Related Reading
- Cybersec
- Git Interview Questions
- Front End Developer Interview Questions
- DevOps Interview Questions And Answers
- Leetcode Roadmap
- Leetcode Alternatives
- System Design Interview Preparation
- Ansible Interview Questions
- Engineering Levels
- jQuery Interview Questions
- ML Interview Questions
- Selenium Interview Questions And Answers
- ASP.NET MVC Interview Questions
- NodeJS Interview Questions
- Deep Learning Interview Questions
- LockedIn
Nail Coding Interviews with Interview Coder's Undetectable Coding Assistant − Get Your Dream Job Today
Grinding LeetCode for months to pass one tech interview? There's a smarter way. Interview Coder is your AI-powered, undetectable coding assistant for coding interviews, completely undetectable and invisible to screen sharing. While your classmates stress over thousands of practice problems, you'll have an AI assistant that solves coding challenges in real-time during your actual interviews.
Used by 87,000+ developers landing offers at FAANG, Big Tech, and top startups. Stop letting LeetCode anxiety kill your confidence. Join the thousands who've already taken the shortcut to their dream job. Download Interview Coder and turn your following coding interview into a guaranteed win.
Related Reading
- Coding Interview Tools
- Jira Interview Questions
- Coding Interview Platforms
- Common Algorithms For Interviews
- Questions To Ask Interviewer Software Engineer
- Java Selenium Interview Questions
- Python Basic Interview Questions
- RPA Interview Questions
- Angular 6 Interview Questions
- Best Job Boards For Software Engineers
- Leetcode Cheat Sheet
- Software Engineer Interview Prep
- Technical Interview Cheat Sheet
- Common C# Interview Questions
Take The Short Way
Stop Grinding. Start Getting Offers