Paramclasses Academy - Blog

Tutorials Details

←
Post 28 of 29
→

React.js Interview Questions and Answers — Beginner to Advanced

React.js Interview Questions and Answers — Beginner to Advanced

October 30, 2026

1. Introduction

React.js is one of the most popular JavaScript libraries for building modern user interfaces. Many companies use React to develop interactive websites, dashboards, e-commerce applications, and web applications.

In React interviews, interviewers generally ask questions about:

  • React fundamentals

  • Components and JSX

  • Props and State

  • React Hooks

  • Event Handling

  • Conditional Rendering

  • Lists and Keys

  • Forms

  • React Router

  • Context API

  • Performance Optimization

  • Advanced React Concepts

In this tutorial, we will cover important React interview questions with simple explanations and practical examples.


2. Beginner-Level React Interview Questions

Q1. What is React.js?

Definition:

React.js is an open-source JavaScript library used to build interactive and reusable user interfaces, especially for web applications.

Simple Explanation:

React helps developers divide a website into small reusable components. These components can be combined to create complete user interfaces.

Example:

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

export default App;

Interview-Ready Answer:

"React.js is an open-source JavaScript library developed by Meta for building interactive and reusable user interfaces using a component-based architecture."


Q2. Who developed React.js?

Definition:

React was developed by Facebook, now known as Meta, and was initially released publicly in 2013.

Simple Explanation:

React was created to help developers build complex user interfaces more efficiently.

Interview-Ready Answer:

"React.js was developed by Facebook, now Meta, and was first released as an open-source library in 2013."


Q3. What are the main features of React?

Definition:

Features are the capabilities that make React useful for developing user interfaces.

Important Features:

  1. Component-Based Architecture

  2. JSX

  3. Virtual DOM

  4. One-Way Data Flow

  5. Reusable Components

  6. React Hooks

  7. Declarative UI Development

Interview-Ready Answer:

"The main features of React include component-based architecture, JSX, Virtual DOM, one-way data flow, reusable components, and Hooks."


Q4. What is a component in React?

Definition:

A component is an independent and reusable piece of a user interface that can contain its own logic and presentation.

Simple Explanation:

For example, a website may have a Header, Navbar, Footer, Sidebar, and Product Card. Each of these can be developed as a separate React component.

Example:

function Header() {
  return (
    <h1>My Website</h1>
  );
}

export default Header;

Interview-Ready Answer:

"A component in React is a reusable building block of the user interface. It helps divide a large application into smaller and manageable parts."


Q5. What are the types of components in React?

Definition:

React components are commonly categorized by how they are defined.

Main Types:

  1. Functional Components

  2. Class Components

Functional Component Example:

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

Class Component Example:

import { Component } from "react";

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

Interview-Ready Answer:

"React supports functional components and class components. Functional components are JavaScript functions that return UI, while class components are ES6 classes that extend React.Component. Modern React development generally prefers functional components with Hooks."


Q6. What is JSX in React?

Definition:

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows developers to write HTML-like markup inside JavaScript code.

Simple Explanation:

JSX makes React code easier to read and write because we can describe the user interface using HTML-like syntax.

Example:

function App() {
  const name = "Niranjan";

  return (
    <h1>Hello, {name}</h1>
  );
}

Interview-Ready Answer:

"JSX stands for JavaScript XML. It is a syntax extension that allows us to write HTML-like markup inside JavaScript for describing React user interfaces."


Q7. What is the Virtual DOM?

Definition:

The Virtual DOM is an in-memory representation of the UI that React uses to determine what changes need to be applied to the actual DOM.

Simple Explanation:

When the application state changes, React calculates the required UI updates and applies the necessary changes to the browser DOM.

Interview-Ready Answer:

"The Virtual DOM is an in-memory representation of the user interface. React uses it to calculate UI changes and update the actual DOM efficiently."


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

Definition:

The Real DOM represents the actual document structure in the browser, whereas the Virtual DOM represents the UI in memory.

Real DOM Virtual DOM
Exists in the browser Exists in memory
Represents the actual page Represents the UI structure
Updated through DOM operations Used by React to calculate updates
Browser manages it React manages its UI representation

Interview-Ready Answer:

"The Real DOM is the actual document structure rendered by the browser, whereas the Virtual DOM is an in-memory representation used by React to calculate and manage UI updates."


Q9. What is the difference between HTML and JSX?

Definition:

HTML is a markup language used to structure web pages. JSX is a JavaScript syntax extension used to describe React user interfaces.

HTML JSX
Used to structure web pages Used to describe React UI
Uses class Uses className
Uses for for labels Uses htmlFor
JavaScript expressions are not directly embedded in markup JavaScript expressions can be written inside {}
Event attributes use HTML conventions Events use camelCase, such as onClick

Example:

function App() {
  const message = "Hello";

  return (
    <div className="container">
      <h1>{message}</h1>
      <button onClick={() => alert("Hello!")}>
        Click Me
      </button>
    </div>
  );
}

Interview-Ready Answer:

"HTML is a markup language for structuring web pages, while JSX is a JavaScript syntax extension that allows us to write HTML-like UI descriptions inside React code."


Q10. What are Props in React?

Definition:

Props, short for properties, are read-only inputs passed from a parent component to a child component.

Simple Explanation:

Props allow components to receive data from other components.

Example:

function User({ name }) {
  return <h2>Hello, {name}</h2>;
}

function App() {
  return (
    <User name="Rahul" />
  );
}

export default App;

Interview-Ready Answer:

"Props are read-only inputs used to pass data from a parent component to a child component. They help make components reusable and dynamic."


Q11. What is State in React?

Definition:

State is data managed by a React component that can change over time and influence what the component displays.

Simple Explanation:

For example, a counter value, login status, search text, and selected theme can be stored in state.

Example:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

Interview-Ready Answer:

"State is component-managed data that can change over time. When state is updated using React's state update mechanism, React can render the component again to reflect the updated data."


Q12. What is the difference between Props and State?

Props State
Passed from parent to child Managed by a component
Read-only from the receiving component's perspective Updated using state setters or reducers
Used to pass data Used to manage changing data
Controlled by the parent Controlled by the component or its state owner

Example:

import { useState } from "react";

function Child({ title }) {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>{title}</h2>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

function App() {
  return <Child title="My Counter" />;
}

Interview-Ready Answer:

"Props are read-only inputs passed from a parent component, whereas state is data managed within a component or its state owner and can change over time."


3. Intermediate-Level React Interview Questions

Q13. What are React Hooks?

Definition:

Hooks are special React functions that allow functional components to use React features such as state, context, references, and effects.

Examples of Hooks:

  • useState

  • useEffect

  • useContext

  • useRef

  • useReducer

  • useMemo

  • useCallback

Interview-Ready Answer:

"React Hooks are special functions that allow functional components to use React features such as state management, side effects, context, and references without writing class components."


Q14. What is the useState Hook?

Definition:

useState is a React Hook used to add and manage state in functional components.

Syntax:

const [state, setState] = useState(initialValue);

Example:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <>
      <h2>{count}</h2>

      <button onClick={() => setCount((previous) => previous + 1)}>
        Increase
      </button>
    </>
  );
}

Explanation:

  • count stores the current state value.

  • setCount updates the state.

  • useState(0) provides the initial value.

Interview-Ready Answer:

"The useState Hook allows functional components to manage state. It returns the current state value and a setter function used to update that state."


Q15. What is the useEffect Hook?

Definition:

useEffect is a React Hook used to synchronize a component with external systems, such as APIs, subscriptions, browser APIs, and timers.

Syntax:

useEffect(() => {
  // Effect logic

  return () => {
    // Cleanup logic
  };
}, [dependencies]);

Example:

import { useEffect, useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <button onClick={() => setCount((previous) => previous + 1)}>
      Count: {count}
    </button>
  );
}

Interview-Ready Answer:

"The useEffect Hook is used to synchronize a React component with external systems. It can run after commits, respond to dependency changes, and perform cleanup when necessary."


Q16. What is the difference between useState and useEffect?

useState useEffect
Manages component state Synchronizes with external systems
Returns state and setter Does not return state
Used for changing UI data Used for effects such as subscriptions and API synchronization
State updates can trigger rendering Effects run after React commits the UI

Interview-Ready Answer:

"useState is used to manage component data, whereas useEffect is used to synchronize a component with external systems such as APIs, timers, and event subscriptions."


Q17. What is Conditional Rendering?

Definition:

Conditional Rendering means displaying different UI elements based on a condition.

Example:

function App() {
  const isLoggedIn = true;

  return (
    <div>
      {isLoggedIn ? (
        <h2>Welcome User</h2>
      ) : (
        <h2>Please Login</h2>
      )}
    </div>
  );
}

Common Methods:

  • if/else

  • Ternary operator

  • Logical AND (&&)

  • Switch statements

Interview-Ready Answer:

"Conditional rendering is a technique in React that allows us to display different UI elements based on conditions or application state."


Q18. How do you render a list in React?

Definition:

List rendering means displaying multiple elements from an array using JavaScript methods such as map().

Example:

function App() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

Interview-Ready Answer:

"In React, we commonly use the JavaScript map() method to render lists of elements from arrays. Each rendered item should have a stable and unique key."


Q19. What is the purpose of the key prop in React?

Definition:

A key is a special attribute that helps React identify individual elements in a list across renders.

Example:

const users = [
  { id: 1, name: "Rahul" },
  { id: 2, name: "Amit" }
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Interview-Ready Answer:

"The key prop helps React identify list items across renders. It supports correct reconciliation when items are added, removed, or reordered."


Q20. What is Event Handling in React?

Definition:

Event handling is the process of responding to user interactions such as clicks, typing, form submissions, and keyboard actions.

Example:

function App() {
  function handleClick() {
    alert("Button Clicked!");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}

Important Event Handlers:

  • onClick

  • onChange

  • onSubmit

  • onMouseOver

  • onKeyDown

Interview-Ready Answer:

"Event handling in React allows components to respond to user interactions. React event handlers are commonly written using camelCase names, such as onClick and onChange."


Q21. What are Controlled and Uncontrolled Components?

Definition:

A controlled form component receives its value from React state, whereas an uncontrolled form component stores its current value in the DOM and is commonly accessed using a ref.

Controlled Component Example:

import { useState } from "react";

function App() {
  const [name, setName] = useState("");

  return (
    <input
      value={name}
      onChange={(event) => setName(event.target.value)}
    />
  );
}

Uncontrolled Component Example:

import { useRef } from "react";

function App() {
  const inputRef = useRef(null);

  function handleSubmit() {
    alert(inputRef.current.value);
  }

  return (
    <>
      <input ref={inputRef} />

      <button onClick={handleSubmit}>
        Submit
      </button>
    </>
  );
}

Interview-Ready Answer:

"A controlled component gets its form value from React state, while an uncontrolled component manages its value through the DOM, often accessed using a ref."


Q22. What is React Context API?

Definition:

Context is a React feature used to share data across a component tree without passing props through every intermediate component.

Simple Explanation:

Suppose an application has a theme setting. Instead of passing the theme through many components, we can share it through Context.

Example:

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function Home() {
  const theme = useContext(ThemeContext);

  return <h2>Current Theme: {theme}</h2>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Home />
    </ThemeContext.Provider>
  );
}

Interview-Ready Answer:

"React Context API allows us to share data across multiple components without manually passing props through every level of the component tree."


Q23. What is Prop Drilling?

Definition:

Prop drilling is the process of passing data through multiple intermediate components to reach a deeply nested child component.

Example:

function App() {
  const user = "Rahul";

  return <Parent user={user} />;
}

function Parent({ user }) {
  return <Child user={user} />;
}

function Child({ user }) {
  return <h2>Hello {user}</h2>;
}

Simple Explanation:

Here, the Parent component receives and forwards the user prop even though it does not need to use the data itself.

Interview-Ready Answer:

"Prop drilling occurs when data is passed through multiple intermediate components to reach a deeply nested component. Context or other state management approaches can help reduce unnecessary prop passing."


Q24. What is React Router?

Definition:

React Router is a routing library used to manage navigation between different views or routes in a React application.

Example:

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

function Home() {
  return <h1>Home Page</h1>;
}

function About() {
  return <h1>About Page</h1>;
}

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

Interview-Ready Answer:

"React Router is a routing library that allows us to create navigation and multiple route-based views in React applications without requiring a full browser page reload for normal client-side navigation."


Q25. What is the useRef Hook?

Definition:

useRef is a React Hook that stores a mutable value which persists between renders without triggering a re-render when changed.

Example:

import { useRef } from "react";

function App() {
  const inputRef = useRef(null);

  function focusInput() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />

      <button onClick={focusInput}>
        Focus Input
      </button>
    </>
  );
}

Interview-Ready Answer:

"The useRef Hook creates a mutable reference whose value persists between renders. It is commonly used to access DOM elements or store values that should not trigger a re-render."


4. Advanced-Level React Interview Questions

Q26. What is the useMemo Hook?

Definition:

useMemo is a React Hook that caches the result of a calculation between renders until its dependencies change.

Example:

import { useMemo, useState } from "react";

function App() {
  const [number, setNumber] = useState(5);

  const result = useMemo(() => {
    return number * number;
  }, [number]);

  return (
    <div>
      <h2>Square: {result}</h2>

      <button onClick={() => setNumber((n) => n + 1)}>
        Increase
      </button>
    </div>
  );
}

Interview-Ready Answer:

"useMemo is a React Hook that caches the result of a calculation between renders and recomputes it when its dependencies change. It can help avoid unnecessary expensive calculations."


Q27. What is the useCallback Hook?

Definition:

useCallback is a React Hook that caches a function definition between renders until its dependencies change.

Example:

import { useCallback, useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    console.log("Button clicked");
  }, []);

  return (
    <div>
      <h2>{count}</h2>

      <button onClick={() => setCount((n) => n + 1)}>
        Increase
      </button>

      <button onClick={handleClick}>
        Log Message
      </button>
    </div>
  );
}

Interview-Ready Answer:

"useCallback is a React Hook that caches a function definition between renders. It is useful when function identity matters, such as when passing callbacks to memoized child components."


Q28. What is the difference between useMemo and useCallback?

useMemo useCallback
Caches a calculated value Caches a function definition
Used for expensive calculations Used when function identity matters
Returns the cached calculation result Returns the cached function

Example:

const total = useMemo(() => {
  return price * quantity;
}, [price, quantity]);

const handleClick = useCallback(() => {
  console.log("Clicked");
}, []);

Interview-Ready Answer:

"useMemo caches the result of a calculation, whereas useCallback caches a function definition. Both can help with performance optimization when used appropriately."


Q29. What is the useReducer Hook?

Definition:

useReducer is a React Hook used to manage state through a reducer function and dispatched actions.

Example:

import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };

    case "DECREMENT":
      return { count: state.count - 1 };

    default:
      return state;
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, {
    count: 0
  });

  return (
    <div>
      <h2>{state.count}</h2>

      <button
        onClick={() => dispatch({ type: "INCREMENT" })}
      >
        Increase
      </button>

      <button
        onClick={() => dispatch({ type: "DECREMENT" })}
      >
        Decrease
      </button>
    </div>
  );
}

Interview-Ready Answer:

"useReducer is a React Hook used to manage state with a reducer function. It is especially useful when state transitions are complex or involve multiple related actions."


Q30. What is React.memo?

Definition:

memo is a React API that can skip re-rendering a component when its props have not changed according to its comparison.

Example:

import { memo, useState } from "react";

const User = memo(function User({ name }) {
  console.log("User component rendered");

  return <h2>Hello, {name}</h2>;
});

function App() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <User name="Rahul" />

      <button onClick={() => setCount((n) => n + 1)}>
        Count: {count}
      </button>
    </div>
  );
}

Interview-Ready Answer:

"React.memo is a component memoization API that can prevent a component from re-rendering when its props remain unchanged. It is useful when profiling shows that avoiding those renders improves performance."


Q31. What is a Custom Hook?

Definition:

A Custom Hook is a JavaScript function whose name starts with use and which can call other React Hooks to reuse stateful logic between components.

Example:

import { useState } from "react";

function useCounter() {
  const [count, setCount] = useState(0);

  function increase() {
    setCount((previous) => previous + 1);
  }

  function decrease() {
    setCount((previous) => previous - 1);
  }

  return {
    count,
    increase,
    decrease
  };
}

function App() {
  const { count, increase, decrease } = useCounter();

  return (
    <div>
      <h2>{count}</h2>

      <button onClick={increase}>Increase</button>
      <button onClick={decrease}>Decrease</button>
    </div>
  );
}

Interview-Ready Answer:

"A Custom Hook is a reusable JavaScript function that uses React Hooks to share stateful logic between components. Its name should start with the word use."


Q32. What is Lazy Loading in React?

Definition:

Lazy loading is a technique used to load certain components or resources only when they are needed.

Example:

import {
  lazy,
  Suspense
} from "react";

const Dashboard = lazy(() => import("./Dashboard"));

function App() {
  return (
    <Suspense fallback={<p>Loading Dashboard...</p>}>
      <Dashboard />
    </Suspense>
  );
}

export default App;

Interview-Ready Answer:

"React.lazy allows us to load a component dynamically when it is rendered. It is commonly used with Suspense to implement component-level code splitting."


Q33. What is Code Splitting?

Definition:

Code splitting is a technique that divides an application's JavaScript bundle into smaller chunks that can be loaded when required.

Simple Explanation:

Instead of loading all application code at once, we can load certain parts only when users need them.

Interview-Ready Answer:

"Code splitting divides an application's JavaScript code into smaller bundles. This can reduce the initial amount of JavaScript that needs to be loaded."


Q34. What is Reconciliation in React?

Definition:

Reconciliation is the process React uses to compare the previous and next UI descriptions and determine the necessary updates.

Simple Explanation:

When state or props change, React works out which parts of the UI need to be updated.

Interview-Ready Answer:

"Reconciliation is React's process of comparing the previous and next rendered UI trees to determine the updates required for the user interface."


Q35. What is the difference between Functional and Class Components?

Functional Components Class Components
Defined as JavaScript functions Defined as ES6 classes
Use Hooks for React features Use lifecycle methods and class state
Generally simpler and more concise Often contain more boilerplate
Preferred in modern React development Still supported by React

Interview-Ready Answer:

"Functional components are JavaScript functions that return UI and can use Hooks. Class components are ES6 classes that extend React.Component and use lifecycle methods. Functional components are generally preferred in modern React development."


Q36. What is the difference between useEffect and useLayoutEffect?

Definition:

Both Hooks synchronize a component with external systems, but they differ in when their effects run.

useEffect useLayoutEffect
Runs after React commits the UI Runs after DOM changes but before the browser repaints
Usually preferred for most effects Used when layout measurement or synchronous visual adjustment is needed
Does not block repaint in the usual case Can block browser repaint

Example:

import { useEffect, useLayoutEffect } from "react";

function App() {
  useEffect(() => {
    console.log("useEffect");
  }, []);

  useLayoutEffect(() => {
    console.log("useLayoutEffect");
  }, []);

  return <h1>Hello React</h1>;
}

Interview-Ready Answer:

"useEffect runs after React commits the UI and is suitable for most effects. useLayoutEffect runs after DOM changes but before the browser repaints, making it useful for layout measurements and visual adjustments."


Q37. What is Error Boundary in React?

Definition:

An Error Boundary is a React component that catches rendering errors in its descendant component tree and displays a fallback UI.

Simple Explanation:

Suppose a child component crashes during rendering. An Error Boundary can display a fallback screen instead of allowing the error to break the entire protected part of the UI.

Example:

import { Component } from "react";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false
    };
  }

  static getDerivedStateFromError() {
    return {
      hasError: true
    };
  }

  componentDidCatch(error, info) {
    console.error("Caught error:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

Usage:

<ErrorBoundary>
  <Dashboard />
</ErrorBoundary>

Interview-Ready Answer:

"An Error Boundary is a React component that catches errors during rendering in its descendant component tree and displays fallback UI. Traditional Error Boundaries are implemented using class component lifecycle methods."


Q38. What is StrictMode in React?

Definition:

StrictMode is a React development tool that helps identify potential problems in an application.

Example:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

ReactDOM.createRoot(
  document.getElementById("root")
).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Simple Explanation:

StrictMode enables additional development checks. In development, React may intentionally call certain functions more than once to help reveal unsafe side effects.

Interview-Ready Answer:

"React StrictMode is a development-only tool that helps identify potential problems, unsafe patterns, and side-effect issues. It does not affect production rendering."


Q39. What is Lifting State Up in React?

Definition:

Lifting state up means moving shared state to the closest common parent component so that multiple child components can access and update it through props.

Simple Explanation:

If two child components need the same data, we can store that data in their common parent and pass the required values and functions to both children.

Interview-Ready Answer:

"Lifting state up is a React pattern in which shared state is moved to the nearest common parent component so multiple child components can stay synchronized."


Q40. What is the difference between CSR and SSR?

Definition:

CSR stands for Client-Side Rendering, while SSR stands for Server-Side Rendering.

CSR SSR
UI is primarily rendered in the browser HTML is rendered on the server
Browser executes application JavaScript to build the UI Server sends rendered HTML to the browser
Often used in client-rendered React applications Supported by frameworks such as Next.js
Initial content may depend on JavaScript loading Can provide initial HTML before client hydration

Interview-Ready Answer:

"Client-Side Rendering builds the user interface primarily in the browser using JavaScript, whereas Server-Side Rendering generates HTML on the server and sends it to the browser."


5. Important React Practical Interview Questions

Q41. How do you pass data from a parent component to a child component?

Answer:

We use props to pass data from a parent component to a child component.

function Child({ message }) {
  return <h2>{message}</h2>;
}

function Parent() {
  return (
    <Child message="Hello from Parent" />
  );
}

Q42. How do you pass data from a child component to a parent component?

Answer:

We pass a callback function from the parent to the child. The child calls that function with the data.

function Child({ sendData }) {
  return (
    <button onClick={() => sendData("Hello Parent")}>
      Send Data
    </button>
  );
}

function Parent() {
  function receiveData(message) {
    console.log(message);
  }

  return <Child sendData={receiveData} />;
}

Q43. How do you make an API call in React?

Answer:

We can use fetch() inside an effect to request data from an API.

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    async function getUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users"
        );

        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }

        const data = await response.json();

        setUsers(data);
      } catch (error) {
        console.error(error);
      }
    }

    getUsers();
  }, []);

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default Users;

Q44. How do you update an object in React state?

Answer:

We use the state setter and spread syntax to create a new object with the updated property.

import { useState } from "react";

function App() {
  const [user, setUser] = useState({
    name: "Rahul",
    age: 22
  });

  function updateName() {
    setUser((previous) => ({
      ...previous,
      name: "Amit"
    }));
  }

  return (
    <div>
      <h2>{user.name}</h2>
      <h3>{user.age}</h3>

      <button onClick={updateName}>
        Update Name
      </button>
    </div>
  );
}

Q45. How do you update an array in React state?

Answer:

We can use array methods such as map(), filter(), and spread syntax to create a new array.

import { useState } from "react";

function App() {
  const [items, setItems] = useState([
    "Apple",
    "Banana"
  ]);

  function addItem() {
    setItems((previous) => [
      ...previous,
      "Mango"
    ]);
  }

  return (
    <div>
      {items.map((item) => (
        <p key={item}>{item}</p>
      ))}

      <button onClick={addItem}>
        Add Item
      </button>
    </div>
  );
}

6. Common React Interview Mistakes

Avoid these mistakes during technical interviews:

  1. Confusing props with state.

  2. Forgetting the key prop while rendering lists.

  3. Updating state directly.

  4. Calling Hooks inside loops or conditions.

  5. Using useEffect for every calculation.

  6. Ignoring effect dependencies.

  7. Mutating arrays and objects in state.

  8. Using array indexes as keys when list items can move or change.

  9. Assuming React.memo prevents every possible re-render.

  10. Assuming frontend route protection secures backend APIs.

Important Rules of Hooks

  • Call Hooks at the top level of React function components or custom Hooks.

  • Do not call Hooks inside loops, conditions, or nested functions.

  • Custom Hook names should start with use.

  • Follow the Rules of Hooks consistently.


7. Tips for Giving Better Interview Answers

When an interviewer asks a React question:

  1. Start with a clear definition.

  2. Explain the concept in simple words.

  3. Mention its purpose.

  4. Give a small practical example.

  5. Explain where it is used in real applications.

For example, if the interviewer asks, "What is useState?"

A strong answer should explain what it is, why it is used, what it returns, and provide a short example.

Do not memorize answers without understanding their concepts.


8. Practice Exercises

Try answering these questions without looking at the answers above.

  1. What is React.js?

  2. What is JSX?

  3. What is a component?

  4. What is the Virtual DOM?

  5. What are props?

  6. What is state?

  7. What is the difference between props and state?

  8. What are React Hooks?

  9. What is useState?

  10. What is useEffect?

  11. What is conditional rendering?

  12. Why are keys important?

  13. What is Context API?

  14. What is prop drilling?

  15. What is React Router?

  16. What is useRef?

  17. What is useMemo?

  18. What is useCallback?

  19. What is useReducer?

  20. What is React.memo?

  21. What is a Custom Hook?

  22. What is lazy loading?

  23. What is reconciliation?

  24. What is an Error Boundary?

  25. What is StrictMode?

  26. What is lifting state up?

  27. What is the difference between CSR and SSR?

  28. How do you fetch API data in React?

  29. How do you update an object in state?

  30. How do you optimize React performance?


9. Key Takeaways

In this tutorial, we covered important React.js interview questions from beginner to advanced levels.

You learned about:

  • React fundamentals and architecture.

  • JSX and components.

  • Props and state.

  • Virtual DOM and reconciliation.

  • React Hooks.

  • Event handling and conditional rendering.

  • Forms and routing.

  • Context API and prop drilling.

  • Performance optimization.

  • Advanced React concepts.

  • Practical coding interview questions.

Interview Preparation Tip: Focus on understanding concepts and writing code independently. Interviewers often ask follow-up questions to check whether you understand how React works in real applications.

←
Post 28 of 29
→