React

React

Top Interview Questions

About React

 

React is a popular open-source JavaScript library used for building user interfaces, especially single-page applications (SPAs). Developed and maintained by Facebook (now Meta) and a large open-source community, React has become one of the most widely used frontend technologies in modern web development. Its component-based architecture, performance optimizations, and flexibility make it a preferred choice for developers building scalable and maintainable applications.

Introduction to React

React was first released in 2013 by Facebook to solve the problem of efficiently updating and rendering dynamic user interfaces. Traditional approaches using direct DOM manipulation were slow and difficult to manage as applications grew in size and complexity. React introduced a declarative programming model, where developers describe what the UI should look like for a given state, and React takes care of updating the UI when the state changes.

At its core, React focuses only on the view layer of an application. Unlike full-fledged frameworks such as Angular, React is a library that can be combined with other tools and libraries to build complete applications. This flexibility allows developers to choose routing, state management, and data-fetching solutions according to project needs.

Component-Based Architecture

One of React’s most important concepts is the component-based architecture. A component is a reusable, self-contained piece of UI that defines how a part of the interface should appear and behave. Components can be as simple as a button or as complex as an entire page.

React supports two main types of components:

  • Functional components, which are JavaScript functions that return JSX.

  • Class components, which are ES6 classes extending React.Component (less common today).

With the introduction of React Hooks, functional components have become the standard way of writing React code. Hooks allow developers to manage state, lifecycle methods, and side effects without using class components. This has simplified React development and improved code readability and reusability.

JSX: JavaScript with Markup

React uses JSX (JavaScript XML), a syntax extension that allows developers to write HTML-like code inside JavaScript. JSX makes UI code more readable and expressive by keeping structure and logic together.

Although JSX looks like HTML, it is actually compiled into JavaScript function calls. This allows React to create lightweight JavaScript objects representing UI elements. By combining JavaScript logic and UI markup, developers can easily build dynamic and interactive interfaces.

Virtual DOM and Performance

One of the key reasons behind React’s performance is the Virtual DOM. Instead of directly updating the real DOM every time the application state changes, React creates a virtual representation of the DOM in memory. When a change occurs, React compares the new virtual DOM with the previous one using a process called diffing.

After identifying the minimal set of changes, React updates only the necessary parts of the real DOM. This approach significantly improves performance, especially in applications with frequent UI updates, such as dashboards, real-time applications, and complex forms.

State and Props

React applications rely heavily on state and props to manage data and control UI behavior.

  • Props (properties) are read-only values passed from a parent component to a child component. They allow data to flow in one direction, making the application easier to understand and debug.

  • State is mutable data managed within a component. When the state changes, React automatically re-renders the component to reflect the new data.

This unidirectional data flow is a core principle of React and helps maintain predictable application behavior.

React Hooks

Hooks were introduced in React 16.8 and revolutionized the way developers write React components. Some commonly used hooks include:

  • useState – Manages state in functional components.

  • useEffect – Handles side effects such as data fetching, subscriptions, and DOM updates.

  • useContext – Provides a way to share data across components without prop drilling.

  • useRef – Accesses DOM elements or persists values across renders.

  • useMemo and useCallback – Optimize performance by memoizing values and functions.

Hooks promote cleaner code, better separation of concerns, and improved reusability through custom hooks.

Routing in React

Since React focuses only on the UI layer, routing is handled using third-party libraries. The most popular routing solution is React Router. It enables developers to create single-page applications with multiple views and URLs.

React Router allows navigation without reloading the page, improving performance and user experience. It also supports features such as dynamic routing, nested routes, and route-based code splitting.

State Management

For small applications, React’s built-in state management using useState and useContext is sufficient. However, as applications grow, managing shared state across many components can become challenging.

To address this, developers often use external state management libraries such as:

  • Redux

  • Zustand

  • MobX

  • Recoil

Redux, in particular, has been widely adopted for managing complex application state in a predictable and centralized manner. Modern Redux with Redux Toolkit has simplified configuration and reduced boilerplate code.

Ecosystem and Tooling

React has a rich ecosystem of tools and libraries that enhance development productivity. Some popular tools include:

  • Create React App (CRA) – A quick way to set up a React project.

  • Vite – A fast build tool and development server.

  • Next.js – A React framework for server-side rendering and static site generation.

  • ESLint and Prettier – Tools for code quality and formatting.

  • Jest and React Testing Library – Testing tools for React applications.

This ecosystem allows developers to build everything from small projects to large enterprise-level applications.

React in Modern Web Development

React is widely used by companies such as Facebook, Instagram, Netflix, Airbnb, and Uber. Its popularity is driven by its flexibility, strong community support, and continuous improvements. React’s ability to integrate with other libraries and frameworks makes it suitable for a wide range of use cases, including web apps, mobile apps (using React Native), and even desktop applications.

Advantages of React

Some key advantages of React include:

  • Reusable components that reduce code duplication

  • High performance due to the Virtual DOM

  • Strong community and extensive ecosystem

  • Easy integration with other libraries

  • Declarative and predictable UI updates

Fresher Interview Questions

 

1. What is React?

Answer:
React is an open-source JavaScript library developed by Facebook (Meta) for building user interfaces, especially single-page applications (SPAs). It allows developers to create reusable UI components and efficiently update the UI when data changes.

Key points:

  • Component-based architecture

  • Uses Virtual DOM

  • Declarative UI

  • Fast and scalable


2. What are the main features of React?

Answer:
React provides several powerful features:

  1. Component-Based Architecture – UI is divided into reusable components

  2. Virtual DOM – Improves performance

  3. JSX – HTML-like syntax inside JavaScript

  4. Unidirectional Data Flow – Data flows from parent to child

  5. Hooks – Add state and lifecycle features to functional components


3. What is JSX?

Answer:
JSX stands for JavaScript XML. It allows writing HTML-like code inside JavaScript.

Example:

const element = <h1>Hello React</h1>;

Why JSX?

  • Makes code readable

  • Easy to write UI logic

  • Prevents injection attacks


4. What is Virtual DOM?

Answer:
The Virtual DOM is a lightweight copy of the real DOM. React updates the Virtual DOM first and then compares it with the previous version using a process called diffing.

Only the changed parts are updated in the real DOM, improving performance.


5. What is a Component in React?

Answer:
A component is a reusable piece of UI. Each component can have its own logic and design.

Types of components:

  1. Functional Components (Recommended)

  2. Class Components (Older approach)


6. What is a Functional Component?

Answer:
A functional component is a JavaScript function that returns JSX.

Example:

function Welcome() {
  return <h1>Welcome to React</h1>;
}

7. What are Props?

Answer:
Props (properties) are read-only inputs passed from a parent component to a child component.

Example:

function Greeting(props) {
  return <h2>Hello {props.name}</h2>;
}

Key points:

  • Props are immutable

  • Used for component communication


8. What is State in React?

Answer:
State is a built-in object used to store data that can change over time.

Example using useState hook:

const [count, setCount] = React.useState(0);

Difference between Props and State:

Props State
Passed from parent Managed within component
Read-only Can be updated
Immutable Mutable

9. What are Hooks in React?

Answer:
Hooks allow functional components to use state and lifecycle features.

Common Hooks:

  • useState

  • useEffect

  • useContext

  • useRef

  • useMemo


10. What is useEffect?

Answer:
useEffect is used to perform side effects like API calls, subscriptions, or DOM updates.

Example:

useEffect(() => {
  console.log("Component mounted");
}, []);

11. What is the difference between useEffect and componentDidMount?

Answer:

  • componentDidMount is used in class components

  • useEffect is used in functional components

useEffect can handle mount, update, and unmount logic.


12. What is Conditional Rendering?

Answer:
Conditional rendering means displaying components based on a condition.

Example:

{isLoggedIn ? <Dashboard /> : <Login />}

13. What is Event Handling in React?

Answer:
React handles events using camelCase syntax.

Example:

<button onClick={handleClick}>Click Me</button>

14. What are Controlled Components?

Answer:
A controlled component is a form element whose value is controlled by React state.

Example:

<input value={name} onChange={e => setName(e.target.value)} />

15. What is Lifting State Up?

Answer:
When multiple components need the same data, the state is moved to their common parent component.


16. What is Key in React?

Answer:
Keys help React identify which items have changed in a list.

Example:

{items.map(item => (
  <li key={item.id}>{item.name}</li>
))}

17. What is React Router?

Answer:
React Router is used for navigation in React applications.

Example:

<Route path="/about" element={<About />} />

18. What is Context API?

Answer:
Context API allows sharing data globally without passing props manually.

Used for:

  • Theme

  • Authentication

  • Language settings


19. What is Redux?

Answer:
Redux is a state management library used for managing global state in large applications.


20. What are React Fragments?

Answer:
Fragments allow grouping elements without adding extra nodes to the DOM.

Example:

<>
  <h1>Title</h1>
  <p>Description</p>
</>

21. What is Strict Mode?

Answer:
Strict Mode helps identify potential problems during development.

<React.StrictMode>
  <App />
</React.StrictMode>

22. What is Prop Drilling?

Answer:
Prop drilling occurs when props are passed through many levels unnecessarily.

Solution: Context API or Redux.


23. What is Memoization in React?

Answer:
Memoization improves performance by preventing unnecessary re-renders using:

  • React.memo

  • useMemo

  • useCallback


24. What is the difference between React and Angular?

Answer:

React Angular
Library Framework
JSX TypeScript
Flexible Opinionated

25. Why is React popular?

Answer:

  • Fast rendering

  • Reusable components

  • Strong community

  • Backed by Meta

  • Easy to learn


26. What is the difference between Real DOM and Virtual DOM?

Answer:

Real DOM Virtual DOM
Updates entire UI Updates only changed parts
Slower Faster
Direct manipulation Lightweight JS object
High memory usage Efficient memory usage

Explanation:
React updates the Virtual DOM first, compares it with the previous version, and then updates only the changed nodes in the Real DOM.


27. What is Reconciliation in React?

Answer:
Reconciliation is the process React uses to compare the new Virtual DOM with the old one to determine what needs to change in the real DOM.

It uses:

  • Diffing algorithm

  • Keys to identify elements


28. What are Pure Components?

Answer:
A Pure Component prevents unnecessary re-renders by doing a shallow comparison of props and state.

In functional components:

export default React.memo(MyComponent);

29. What is React.memo?

Answer:
React.memo is a higher-order component that memorizes a component and re-renders it only when props change.

Used for performance optimization.


30. What is useCallback Hook?

Answer:
useCallback returns a memoized version of a function to prevent re-creation on every render.

Example:

const handleClick = useCallback(() => {
  setCount(count + 1);
}, [count]);

31. What is useMemo Hook?

Answer:
useMemo memorizes the result of a computation.

Example:

const total = useMemo(() => calculateTotal(items), [items]);

Difference:

  • useCallback → memorizes functions

  • useMemo → memorizes values


32. What is useRef Hook?

Answer:
useRef is used to:

  • Access DOM elements

  • Store mutable values without re-render

Example:

const inputRef = useRef();

inputRef.current.focus();

33. What is Forward Ref?

Answer:
forwardRef allows passing refs from parent to child components.

const Input = React.forwardRef((props, ref) => (
  <input ref={ref} />
));

34. What is Higher-Order Component (HOC)?

Answer:
A HOC is a function that takes a component and returns an enhanced component.

Example:

const withAuth = (Component) => (props) => {
  return <Component {...props} />;
};

35. What are Render Props?

Answer:
Render props is a technique where a component shares logic using a function as a prop.


36. What is Lazy Loading in React?

Answer:
Lazy loading loads components only when needed, improving performance.

const About = React.lazy(() => import('./About'));

Used with Suspense.


37. What is Suspense?

Answer:
Suspense shows a fallback UI while loading components.

<Suspense fallback={<Loading />}>
  <About />
</Suspense>

38. What is Error Boundary?

Answer:
Error boundaries catch JavaScript errors in components and display fallback UI.

Implemented only using class components.


39. What is the difference between Controlled and Uncontrolled Components?

Answer:

Controlled Uncontrolled
Managed by state Managed by DOM
More control Less code
Recommended Not preferred

40. What is PropTypes?

Answer:
PropTypes are used for type checking of props.

Component.propTypes = {
  name: PropTypes.string
};

41. What is defaultProps?

Answer:
Used to assign default values to props.


42. What is React Fiber?

Answer:
React Fiber is the new reconciliation engine introduced in React 16 that improves performance and responsiveness.


43. What is useContext Hook?

Answer:
Used to consume context values without wrapping components in Consumer.

const theme = useContext(ThemeContext);

44. What is State Immutability?

Answer:
State should never be modified directly.

❌ Wrong:

state.count++;

βœ… Correct:

setCount(count + 1);

45. What is Batching in React?

Answer:
React groups multiple state updates into a single re-render to improve performance.


46. What is Synthetic Event?

Answer:
React wraps browser events into a Synthetic Event for cross-browser compatibility.


47. What is React Portal?

Answer:
Portals allow rendering components outside the parent DOM hierarchy.

Used for:

  • Modals

  • Tooltips


48. What is Server-Side Rendering (SSR)?

Answer:
SSR renders React components on the server for:

  • Faster load time

  • Better SEO

Used in Next.js.


49. What is Hydration?

Answer:
Hydration attaches React event handlers to server-rendered HTML.


50. What are Common React Interview Mistakes by Freshers?

Answer:

  • Mutating state directly

  • Missing keys in lists

  • Overusing useEffect

  • Not understanding props vs state


51. What is the difference between Class Component and Functional Component?

Class Component Functional Component
Uses extends React.Component JavaScript function
Uses render() method Returns JSX directly
Can have state and lifecycle methods Before hooks, no state or lifecycle; now can with hooks
More boilerplate Less boilerplate
this keyword is used No this keyword

Example Class Component:

class Welcome extends React.Component {
  render() {
    return <h1>Hello {this.props.name}</h1>;
  }
}

Example Functional Component:

function Welcome(props) {
  return <h1>Hello {props.name}</h1>;
}

52. What are React Lifecycle Methods?

Lifecycle methods are available only in class components. They allow you to run code at specific stages of a component’s life.

Phases:

  1. Mounting: Component is created and added to DOM

    • constructor()

    • static getDerivedStateFromProps()

    • render()

    • componentDidMount()

  2. Updating: Component updates due to state/props change

    • shouldComponentUpdate()

    • render()

    • getSnapshotBeforeUpdate()

    • componentDidUpdate()

  3. Unmounting: Component removed from DOM

    • componentWillUnmount()

Functional components now use useEffect to mimic lifecycle behavior.


53. What is the difference between State and Context?

State Context
Managed at component level Managed globally
Triggers re-render in the component Can provide data to multiple components without props drilling
Local updates Shared updates

54. What is Prop Drilling and how to avoid it?

Prop Drilling: Passing props through multiple components unnecessarily.

Example:

<App>
  <Parent prop="value">
    <Child />
  </Parent>
</App>

Solution:

  • Context API

  • Redux / Zustand


55. What is React Router and why is it used?

React Router: A library to handle routing in SPAs.

Features:

  • Declarative routing

  • Nested routes

  • Dynamic routes

  • Navigation without page reload

Example:

import { BrowserRouter, Routes, Route } from "react-router-dom";

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</BrowserRouter>

56. What is the difference between useEffect with empty dependency and without dependency?

// Empty dependency array
useEffect(() => {
  console.log("Runs only once");
}, []);

// No dependency array
useEffect(() => {
  console.log("Runs on every render");
});
  • [] → Mount only

  • No array → Every render


57. What is Controlled vs Uncontrolled Input in React?

Controlled Input: Value controlled by React state

<input value={name} onChange={(e) => setName(e.target.value)} />

Uncontrolled Input: Value handled by DOM, using ref

<input ref={inputRef} />

58. What is the difference between useState and useReducer?

useState useReducer
Simple state logic Complex state logic
Single variable or object Multiple state transitions
Easy to use More structured
Example: const [count, setCount] = useState(0) Example: const [state, dispatch] = useReducer(reducer, initialState)

59. What is the difference between React and React Native?

React React Native
For web apps For mobile apps
Uses HTML and CSS Uses native components (View, Text)
Browser DOM Native UI components
Example: <div> Example: <View>

60. What is the difference between useLayoutEffect and useEffect?

useEffect useLayoutEffect
Runs after rendering Runs synchronously before painting
Doesn’t block DOM Blocks DOM updates
Good for API calls, subscriptions Good for measuring DOM

61. What is React Strict Mode?

StrictMode is a wrapper component that helps detect potential problems in development:

<React.StrictMode>
  <App />
</React.StrictMode>
  • Checks for unsafe lifecycle methods

  • Identifies legacy API usage

  • Double-invokes certain functions in development


62. What is the difference between useRef and createRef?

useRef createRef
Functional components Class components
Persistent between renders New ref created on each render
const ref = useRef() this.ref = React.createRef()

63. What is PureComponent vs Component?

  • Component: Re-renders on any state/prop change

  • PureComponent: Re-renders only if shallow comparison of state/props changes

class MyComponent extends React.PureComponent {}

64. What is Server-Side Rendering (SSR) in React?

  • Pre-renders React components on the server

  • Sends HTML to the browser

  • Benefits: SEO, faster first load

  • Framework: Next.js


65. What is React Portals?

  • Render components outside the parent DOM

  • Useful for modals, tooltips

ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'))

66. What are Higher-Order Components (HOC)?

  • Function that enhances a component

  • Example: Authentication HOC

const withAuth = (Component) => {
  return (props) => {
    return isLoggedIn ? <Component {...props} /> : <Login />;
  };
};

67. What is Lazy Loading in React?

  • Components loaded on demand

  • Improves performance

const About = React.lazy(() => import('./About'));
<Suspense fallback={<Loader />}>
  <About />
</Suspense>

68. How to Optimize React Performance?

  1. Use React.memo for functional components

  2. Use useCallback and useMemo

  3. Avoid unnecessary re-renders

  4. Lazy load components

  5. Split bundle using React.lazy + Suspense


69. What is Event Pooling in React?

  • React wraps native events in a SyntheticEvent

  • Events are pooled to improve performance

  • Use event.persist() to access event asynchronously


70. What is Hydration in React?

  • When using SSR, React attaches event listeners to server-rendered HTML

  • Optimizes client-side rendering

Experienced Interview Questions

 

1. What is the difference between React Hooks and Class Component Lifecycle Methods?

Class Components Functional Components (Hooks)
componentDidMountuseEffect(() => {}, []) useEffect mimics mount, update, unmount
componentDidUpdateuseEffect(() => {}, [deps]) Dependence array controls update behavior
componentWillUnmountreturn () => {} inside useEffect Cleanup function in useEffect handles unmount
State using this.setState useState hook
More boilerplate Less boilerplate, cleaner

Example: Lifecycle with Hooks

useEffect(() => {
  console.log("Component mounted");

  return () => console.log("Component unmounted");
}, []);

2. How does the Virtual DOM diffing algorithm work?

  • React compares the new Virtual DOM tree with the old one (diffing).

  • Only the changed nodes are updated in the real DOM.

  • Keys in lists help React optimize this comparison.

Tip for interviews: Explain O(n) complexity and the importance of keys in dynamic lists.


3. How do you prevent unnecessary re-renders in React?

Techniques:

  1. Use React.memo for functional components

  2. Use PureComponent for class components

  3. Use useCallback for functions passed as props

  4. Use useMemo for expensive calculations

  5. Avoid changing state unnecessarily

Example:

const MemoizedChild = React.memo(Child);

4. What is reconciliation in React?

  • Reconciliation is React’s process of updating the DOM efficiently.

  • React checks which elements changed, were added, or removed.

  • Uses Virtual DOM + keys for optimal updates.

Key point: Always assign unique keys in lists.


5. Explain React Context vs Redux

Context API Redux
Built-in React External library
Ideal for small apps Ideal for large apps
Less boilerplate Centralized state management
No middleware support Middleware: Thunk, Saga

Scenario:

  • Theme toggling → Context

  • Shopping cart state → Redux


6. How would you handle API calls in React efficiently?

  • Use useEffect for fetching data

  • Use async/await

  • Handle loading and error states

  • Cancel subscriptions on unmount using AbortController

Example:

useEffect(() => {
  const controller = new AbortController();
  fetch("https://api.example.com", { signal: controller.signal })
    .then(res => res.json())
    .then(setData)
    .catch(err => console.error(err));

  return () => controller.abort();
}, []);

7. How does React’s useEffect dependency array work?

  • Empty array ([]) → runs once (componentDidMount)

  • No array → runs after every render

  • Array with dependencies → runs when dependencies change

Example:

useEffect(() => {
  console.log(count);
}, [count]); // runs only when count changes

8. Explain the difference between useLayoutEffect and useEffect

useEffect useLayoutEffect
Runs after painting Runs before painting
Non-blocking Blocking
API calls, subscriptions DOM measurements, layout calculations

Scenario: Measuring a div width before render → useLayoutEffect


9. How do you implement code splitting in React?

  • Use React.lazy + Suspense

  • Load components on demand to reduce initial bundle size

const About = React.lazy(() => import('./About'));
<Suspense fallback={<Loader />}>
  <About />
</Suspense>
  • Also possible with dynamic import in routes (React Router).


10. What are Higher-Order Components (HOC) and their use cases?

  • A HOC is a function that takes a component and returns a new component

  • Used for:

    • Authentication (withAuth)

    • Logging

    • Theme wrapping

Example:

const withLogger = (Component) => (props) => {
  console.log("Props:", props);
  return <Component {...props} />;
};

11. Explain the difference between Controlled and Uncontrolled Components

Controlled Components:

  • Value controlled by React state

<input value={name} onChange={(e) => setName(e.target.value)} />

Uncontrolled Components:

  • Value controlled by DOM

<input ref={inputRef} />

Use case: Form validation → Controlled Component


12. How do you optimize performance for large lists?

  1. Virtualizationreact-window or react-virtualized

  2. Keys for stable identity

  3. Memoized list items

  4. Pagination or lazy loading


13. Explain Prop Drilling and how to avoid it

Prop Drilling: Passing props through multiple levels unnecessarily.

Solution:

  • Context API

  • Redux / Zustand / Recoil

<ThemeContext.Provider value={theme}>
  <Component />
</ThemeContext.Provider>

14. How do you handle forms in React?

  • Controlled inputs → React state

  • Uncontrolled inputs → refs

  • Use libraries: Formik, React Hook Form

Example (React Hook Form):

const { register, handleSubmit } = useForm();
<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("name")} />
</form>

15. Explain useReducer and when to use it

  • useReducer is ideal for complex state logic

  • Alternative to useState when multiple state variables depend on each other

const initialState = { count: 0 };
function reducer(state, action) {
  switch(action.type) {
    case 'increment': return { count: state.count + 1 };
    default: return state;
  }
}
const [state, dispatch] = useReducer(reducer, initialState);

16. How do you manage global state in a React application?

Options:

  1. Redux → For large apps with multiple modules

  2. Context API → For small apps

  3. Zustand / Recoil → Lightweight alternative

  4. React Query / SWR → For server state


17. Explain Server-Side Rendering (SSR) and Hydration

  • SSR: React components rendered on server, sent as HTML

  • Hydration: React attaches event listeners to server-rendered HTML

Framework: Next.js


18. How do you debug React applications?

  1. React DevTools → Component tree, props, state

  2. Console.log → Quick debugging

  3. Profiler → Performance bottlenecks

  4. Error Boundaries → Catch errors gracefully


19. How do you handle error boundaries?

  • Only class components can be error boundaries

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return <h1>Something went wrong</h1>;
    return this.props.children;
  }
}

20. How do you optimize React performance for re-renders?

  • React.memo for functional components

  • useCallback / useMemo

  • Avoid anonymous functions in render

  • Split components to minimize re-rendering

  • Lazy load components

  • Virtualize large lists


21. What is the difference between useEffect, useLayoutEffect, and useInsertionEffect?

Hook When it runs Use case
useEffect After the render is painted Fetching API data, subscriptions
useLayoutEffect Before painting the DOM Measuring layout, reading DOM dimensions
useInsertionEffect Before any styles are injected Injecting CSS in libraries like styled-components

Example:

useLayoutEffect(() => {
  const width = divRef.current.offsetWidth;
}, []);

22. What are render props and why are they used?

  • Render props is a pattern where a component receives a function as a prop to render dynamic content.

  • Used to share logic between components without HOC.

Example:

<DataFetcher render={(data) => <List items={data} />} />

23. How does React handle event delegation?

  • React does not attach events directly to DOM nodes.

  • All events are handled via SyntheticEvent at the root (document level).

  • Ensures cross-browser compatibility and better performance.


24. What is the difference between reconciliation with and without keys?

  • With keys: React efficiently reuses elements

  • Without keys: React re-renders all elements unnecessarily

Example:

{items.map(item => <li key={item.id}>{item.name}</li>)}

25. Explain React Fiber Architecture

  • React Fiber (React 16+) is the new reconciliation engine

  • Allows:

    • Incremental rendering

    • Interruptible rendering

    • Prioritizing updates (high vs low priority)

  • Improves responsiveness for complex apps


26. How do you implement error boundaries in functional components?

  • Error boundaries cannot be functional directly

  • Use libraries like react-error-boundary

<ErrorBoundary FallbackComponent={ErrorFallback}>
  <MyComponent />
</ErrorBoundary>

27. What are controlled vs uncontrolled forms in real-world apps?

Controlled forms:

  • React state handles inputs

  • Easier validation

  • Better for dynamic forms

Uncontrolled forms:

  • Use ref for simple forms

  • Less boilerplate

Example (Controlled):

<input value={form.name} onChange={handleChange} />

28. How do you optimize API calls in React apps?

  1. Debouncing inputs to avoid multiple calls

  2. Caching using SWR or React Query

  3. Batching requests to reduce network calls

  4. Canceling requests on unmount with AbortController


29. Explain React.memo and its caveats

  • React.memo prevents re-rendering if props are the same

  • Caveats:

    • Works only for functional components

    • Shallow comparison only

    • Won’t prevent re-render if object/array props change reference

const MemoChild = React.memo(Child);

30. Explain useCallback vs useMemo

Hook Purpose Example
useCallback Memoize function references const memoFn = useCallback(fn, [deps])
useMemo Memoize value/result const memoValue = useMemo(() => computeExpensive(), [deps])

Scenario: Passing functions to child components to avoid unnecessary re-render.


31. What is React Concurrent Mode?

  • Allows interruptible rendering, improves app responsiveness

  • Enables:

    • Suspense for data fetching

    • Rendering without blocking UI

  • Still experimental in React 18+


32. How do you implement lazy loading with React Router v6?

const About = React.lazy(() => import("./About"));

<Routes>
  <Route path="/about" element={
    <Suspense fallback={<Loader />}>
      <About />
    </Suspense>
  }/>
</Routes>
  • Reduces initial bundle size

  • Improves performance


33. Explain hydration and SSR in React

  • SSR (Server-Side Rendering): Server sends pre-rendered HTML

  • Hydration: React attaches event listeners to server HTML

  • Frameworks: Next.js, Remix

Benefit: SEO + faster first paint


34. How do you handle global state in large-scale apps?

Options:

  1. Redux → Centralized state + middleware (Thunk/Saga)

  2. Context API → For small-medium apps

  3. Zustand / Recoil → Lightweight alternatives

  4. React Query / SWR → For server state caching

Tip: Combine Redux + React Query for large apps.


35. How do you prevent performance bottlenecks with large lists?

  1. Virtualizationreact-window, react-virtualized

  2. MemoizationReact.memo for list items

  3. Pagination / Infinite Scroll

  4. Keys for list items


36. How do you test React components?

  1. Unit tests: Jest + React Testing Library

  2. Integration tests: For components working together

  3. E2E tests: Cypress or Playwright

Example (React Testing Library):

render(<Button label="Click me" />);
expect(screen.getByText(/click me/i)).toBeInTheDocument();

37. How do you implement authentication in React apps?

  • JWT / OAuth + API backend

  • Store token: localStorage or httpOnly cookie

  • Use Context API / Redux to store user state

  • Use PrivateRoute component to protect routes

<Route path="/dashboard" element={user ? <Dashboard /> : <Login />} />

38. How do you handle performance issues with useEffect?

  • Avoid unnecessary dependencies

  • Avoid side effects that trigger re-render

  • Use cleanup functions

  • Memoize heavy computations


39. How do you implement theming in React apps?

  • Use Context API for global theme

  • Store user preference in localStorage

  • Example:

<ThemeContext.Provider value={theme}>
  <App />
</ThemeContext.Provider>

40. How do you handle error logging in production React apps?

  1. Error boundaries

  2. External logging services: Sentry, LogRocket

  3. Global API error handling

  4. Monitoring unhandled promise rejections


41. What is the difference between client-side rendering (CSR) and server-side rendering (SSR) in React?

Feature CSR SSR
Render location Browser Server
Initial load Slower (JS downloads first) Faster (HTML already rendered)
SEO Limited SEO-friendly
Hydration Not required Required (attach event listeners)
Framework Create React App Next.js, Remix

Tip: Use SSR for SEO-heavy apps, CSR for dashboard apps.


42. What is React Suspense?

  • Suspense allows pausing the rendering of a component until some condition is met (e.g., data loaded, lazy component imported).

  • Used with React.lazy and data fetching libraries.

<Suspense fallback={<Loader />}>
  <LazyComponent />
</Suspense>

Use case: Lazy loading routes or images.


43. What is the difference between React.lazy and dynamic import?

React.lazy Dynamic Import
Only for components Can be used for any module
Works with Suspense Can work standalone
Clean syntax for lazy components More flexible

44. What are React Portals and their use cases?

  • Portals allow rendering a child component outside the parent DOM hierarchy.

  • Useful for:

    • Modals

    • Tooltips

    • Dropdowns

ReactDOM.createPortal(<Modal />, document.getElementById('modal-root'));

45. Explain React’s SyntheticEvent

  • React wraps native events in SyntheticEvent

  • Provides cross-browser compatibility

  • Pooling mechanism improves performance

Example:

function handleClick(event) {
  console.log(event.type); // SyntheticEvent
}
  • Use event.persist() to retain the event for async calls.


46. How do you handle side effects in React?

  • Use useEffect for:

    • Fetching APIs

    • Subscriptions

    • Timers

    • DOM manipulations

Example:

useEffect(() => {
  const timer = setInterval(() => console.log("tick"), 1000);
  return () => clearInterval(timer); // cleanup
}, []);

47. What is the difference between useState and useReducer?

Feature useState useReducer
State complexity Simple Complex/multi-value
Updates Direct (setState) Action + reducer
Best for Small forms or single value Large forms, multi-step, or nested state

Example (useReducer):

const [state, dispatch] = useReducer(reducer, {count: 0});
dispatch({type: 'increment'});

48. How do you handle memoization in React?

  1. React.memo → Prevent re-rendering functional components

  2. useCallback → Memoize functions

  3. useMemo → Memoize expensive calculations

Example:

const memoizedValue = useMemo(() => computeExpensive(items), [items]);

49. What is React Concurrent Mode?

  • Allows interruptible rendering for responsiveness

  • Prioritizes important updates over less important ones

  • Enables Suspense for data fetching

  • Still experimental

Use case: Rendering a large list without blocking UI.


50. How do you optimize large forms in React?

  1. Use controlled components with minimal re-renders

  2. useReducer to manage form state

  3. Use React Hook Form for performance

  4. Debounce validation

  5. Lazy load optional form sections


51. How do you implement authentication in React?

  • Store JWT tokens securely (httpOnly cookies preferred)

  • Protect routes using PrivateRoute

  • Store user state in Context API or Redux

<Route path="/dashboard" element={user ? <Dashboard /> : <Login />} />

52. How do you handle API error handling?

  1. Wrap API calls in try-catch

  2. Show loading/error states in UI

  3. Cancel API requests on unmount using AbortController

  4. Centralized error handling in Redux middleware or React Query


53. What is the difference between useRef and createRef?

Feature useRef createRef
Functional component βœ… ❌
Class component ❌ βœ…
Persist value between renders βœ… ❌ (new ref on each render)

Example:

const inputRef = useRef();
<input ref={inputRef} />

54. How do you implement global state management?

  • Small apps: Context API

  • Medium apps: Context + useReducer

  • Large apps: Redux / Zustand / Recoil

  • Server state: React Query / SWR

Example (Redux):

const store = configureStore({ reducer: rootReducer });
<Provider store={store}><App /></Provider>

55. How do you optimize React rendering for large lists?

  1. Virtualization: react-window / react-virtualized

  2. Memoization: React.memo for list items

  3. Pagination or infinite scrolling

  4. Keys for list items


56. What is the difference between React.memo, useCallback, and useMemo?

Hook/Method Purpose Example
React.memo Memoize functional components const MemoChild = React.memo(Child)
useCallback Memoize function references const fn = useCallback(() => {}, [deps])
useMemo Memoize computed values const val = useMemo(() => expensive(), [deps])

57. How do you implement code splitting?

  • Use React.lazy + Suspense for lazy-loading components

  • Split bundles for routes using dynamic imports

const About = React.lazy(() => import('./About'));
<Suspense fallback={<Loader />}><About /></Suspense>

58. How do you test React components?

  • Unit tests: Jest + React Testing Library

  • Integration tests: For connected components

  • E2E tests: Cypress / Playwright

Example:

render(<Button label="Click" />);
expect(screen.getByText(/click/i)).toBeInTheDocument();

59. What are some performance pitfalls in React apps?

  1. Unnecessary re-renders (missing memoization)

  2. Updating state incorrectly (mutating objects/arrays)

  3. Large lists without virtualization

  4. Heavy computations inside render

  5. Overusing useEffect without dependency arrays


60. How do you handle styling in React?

  1. CSS Modules → Scoped styles

  2. Styled Components / Emotion → CSS-in-JS

  3. TailwindCSS → Utility-first approach

  4. SASS / SCSS → Preprocessor

  5. Inline styles for dynamic properties