Most Asked React JS Interview Questions and Answers


-

1. What is React?

React is a JavaScript frontend library used for building interactive interfaces using component-based architecture. It uses JSX to build the components. It is maintained by Meta (formerly Facebook).


What is component-based architecture?

Component-based architecture means creating small, reusable pieces of UI, for example, Header, Footer, Button, and Card.


What is JSX

JSX is a JavaScript XML, which allows writing HTML inside JavaScript and JavaScript inside HTML. The browser does not support JSX directly, that's why Babel (JavaScript Compiler) converts JSX to browser-compatible JavaScript

const App = ()=> {

const a = [ "test1" ,"test2" , "test3" ]

return <div> //this is HTML
{a.map((element) => {       // this is JavaScript
return <p> {element} </p>   // P tag is HTML and {element} is JavaScript
})
}
</div>
}

export default App


-

2. What are the features of React?

  1. Component-Based Architecture

  2. JSX ( JavaScript XML)

  3. Virtual DOM

    At the initial render, React creates a copy of the Real DOM, which we call as Virtual DOM.

    But why does React need it?

    Because:

    • Real DOM is slow to manipulate.

    • Frequent UI changes (like in dynamic apps) cause performance issues.

    • React wants to optimize rendering and make updates fast and efficiently.


    But how does it solve the above problems?

    As we know, React creates a copy of the Real DOM at initial render, then when we update state in our application, React again creates a new virtual DOM, then it compares the new Virtual DOM with the previous Virtual DOM and updates only those Nodes which are changed.


    Now, what are Nodes in this context

    In React’s Virtual DOM, a node refers to:

    A unit in the UI tree — typically a JSX element like <div>, <p>, <button>, etc., or even a text string like "Hello".

    Each JSX element becomes a node in the Virtual DOM tree.

  4. Performance Optimization

    React uses a Diffing Algorithm and Reconciliation process to apply minimal changes to the real DOM, boosting performance.


    Now, what is the Diffing Algorithm?

    When React compares the changes between the current virtual DOM and the previous virtual DOM, it is called as Diffing Algorithm.


    Now, what is the Reconciliation process?

    When React updates the Nodes after comparing the changes (after the diffing algorithm), it is called as Reconciliation process.

  5. One-Way Data Binding

    Data flows in one direction, from parent to child via props, which leads to better control and predictability


-

3. What are state and props in React?


Props : Props (short for properties) are used to pass data from one component (usually a parent) to another (usually a child).

What are the characteristics of Props?

  • Read-only
  • Passed from parent to child
  • Used to customize child components
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>; // using prop
}

function App() {
  return <Welcome name="TechTalkRadar" />; // passing prop
}


State : State is a built-in object in React components that stores data that can change over time. When the state changes, the component re-renders to reflect the new data.


What are the characteristics of State ?

  • Managed within the component
  • Mutable (can be updated)
  • Causes re-rendering
import { useState } from 'react';

function Counter() {
 const [count, setCount] = useState(0); // 'count' is state

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

-

4. What is Real DOM?

Real DOM is the actual Tree structure DOM ( Document Object Model ) rendered by browsers. react creates a copy of this DOM to create virtual DOM

Document
└── html
   └── body
       └── div#root
           ├── h1 → "Hello World"
           └── p → "This is a paragraph."


-

5. What is React Hook, and what are the commonly used React Hooks?

React Hook is just a special function in React.

It lets you add features like:

  • Saving data (like a value or input)

  • Running code when something changes


Hooks allow you to do powerful things (like saving state or using lifecycle methods) inside a simple function – no classes needed anymore.

For example:

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

 useEffect(() => {
   // do something
 }, []);

 return <div>{count}</div>;
}


Commonly Used React Hooks

1. useState – to remember things

Think of it like a memory for your component. You can use it to save a value and change it later.

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

Now count starts at 0.
You can call setCount(count + 1) to change it.


2. useEffect – to do something after rendering

Use this when you want to:

  • Call an API

  • Set a timer

  • Listen to changes

Example: Run code after the component shows on screen

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


3. useContext – to share data easily

Sometimes you want to share data (such as a theme or user) with multiple components, without passing it through props repeatedly.

Example: Get user info from shared context

const user = useContext(UserContext);
  1. useRef – to get or store something secretly

This hook we use when we want to store a value without re-rendering the component, or to access an HTML element directly


Example: Focus on an input box

const inputRef = useRef(null);

<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>


5. useMemo – to remember calculated values

When something takes time to calculate, you can use useMemo to remember the result, so it doesn’t recalculate every time.

const result = useMemo(() => slowCalculation(num), [num]);


6. useCallback – to remember functions

If you're passing functions to child components, use useCallback to avoid creating new ones every time.

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


7. useReducer – for managing complex state

This is like useState, but better for more complicated logic, like forms or toggles.

const [state, dispatch] = useReducer(reducer, initialState);

-

6. Explain the useState and useEffect hooks.


What is useState?


useState is a React Hook that lets your function component remember values between renders.


Why do we need useState?


In React, every time something changes (like clicking a button), the component re-renders. If you declare a variable like this:

let count = 0;

It resets to 0 Every time the component re-renders. That’s not helpful for interactive UI.


So we use useState to keep values "alive" between renders.


Syntax of useState

const [value, setValue] = useState(initialValue);
  • value → the current value (like count, name, email)

  • setValue → a function to change the value

  • initialValue → the starting value



Simple Example: Counter

import React, { useState } from "react";

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

 const handleClick = () => {
   setCount(count + 1); // update the count
 };

 return (
   <div>
     <p>You clicked {count} times</p>
     <button onClick={handleClick}>Click Me</button>
   </div>
 );
}

How it works:

  1. When the component renders, count is 0.

  2. When you click the button, setCount(1) is called.

  3. React re-renders the component with count = 1.

  4. You see the updated value on the screen.


The Cycle of useState

User clicks → setState called → React re-renders → New value appears



What is useEffect?


useEffect is a React Hook that lets you run code after a component renders.


If you want to do something when your component loads, updates, or unmounts – like fetching data or setting up a timer – use useEffect.


Why do we need useEffect?

In traditional class components, we had lifecycle methods like:

  • componentDidMount – When the component loads

  • componentDidUpdate – When it updates

  • componentWillUnmount – When it gets removed

But in functional components, we don’t have these methods.


So we use useEffect to handle all of those scenarios.


Syntax of useEffect :

useEffect(() => {
  // Do something here (side effect)

  return () => {
    // Cleanup code (optional)
  };
}, [dependencies]);
  • The first function runs after render
  • The return The part is optional and runs during cleanup
  • [dependencies] tells React when to re-run this code


So,

How does it perform componentDidMount lifecycle

useEffect(() => {
 console.log("Component mounted");
}, []);
  • [] = empty array → runs only once when the component loads
  • Good for: fetching data, setting up event listeners


How does it perform componentDidUpdate lifecycle

useEffect(() => {
  console.log("Count changed:", count);
}, [count]);
  • This effect runs every time count changes.
  • Good for: syncing state, reacting to user input


How does it perform componentWillUnmountlifecycle

Cleanup Function

If your effect creates something that needs cleanup (like a timer, event listener), return a function from useEffect.

useEffect(() => {
 const timer = setInterval(() => {
   console.log("Tick");
 }, 1000);

 // Cleanup function
 return () => {
   clearInterval(timer);
   console.log("Timer cleared");
 };
}, []);
  • Timer starts when the component mounts
  • Timer is cleared when the component unmounts

-

7. What is the purpose of the useReducer hook?


The useReducer Hook is used to manage complex state logic in a React function component, especially when you want a more organized way to manage state updates. useReducer It's like an alternative to useState, but better suited for complicated state logic or multiple related state updates.


const [state, dispatch] = useReducer(reducer, initialState);
  • state: current state
  • dispatch: function to send actions (like setState)
  • reducer: function that updates the state based on an action
  • initialStateStarting value of the state



Counter with useReducer :

import React, { useReducer } from 'react';

const initialState = { count: 0 };

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 Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <h2>Count: {state.count}</h2>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </div>
  );
}


How It Works:

  1. You define a reducer Function – it decides how to update the state based on an action.

  2. dispatch({ type: 'increment' }) sends an action to the reducer.

  3. The reducer returns the new state.

  4. React re-renders the component with the new state.



8. How do you handle routing in React?


In React, routing is handled using a library called React Router. It allows you to:

  • Navigate between different pages (URLs)

  • Show different components based on the URL

  • Pass parameters via the URL

  • Create nested routes and layouts


Step-by-Step: Basic Routing with React Router

  1. Install React Router?


  npm install react-router-dom
  1. Set up the Router in App.js


  import { BrowserRouter, Routes, Route } from "react-router-dom";
  import Home from './Home';
  import About from './About';
  import Contact from './Contact';
  
  function App() {
    return (
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </BrowserRouter>
    );
  }
  
  export default App;
  1. Create Pages (Components)

    // Home.js
    function Home() {
      return <h2>Welcome to the Home Page</h2>;
    }
    export default Home;
    

    Do the same for About.js, Contact.js.


Other Features of React Router


Route Parameters

<Route path="/user/:id" element={<User />} />


Get the param

import { useParams } from "react-router-dom";
const { id } = useParams();


Programmatic Navigation


import { useNavigate } from "react-router-dom";

const navigate = useNavigate();
navigate("/about");


404 Page (Not Found)

<Route path="*" element={<NotFound />} />