Interview Questions

Home Interview Questions

CAREER PREPARATION

React.js Interview Questions and Answers for Freshers: Top Questions to Prepare

React.js Interview Questions and Answers for Freshers: Top Questions to Prepare

Quick Answer

React.js interview questions evaluate a candidate's understanding of component-based development, JSX, props, state, event handling, Hooks, conditional rendering, and application performance. Freshers should understand how React components work, how data flows between components, how Hooks manage state and side effects, and how to build interactive user interfaces. Practical coding experience with forms, lists, API requests, and reusable components is equally important.

Introduction

React.js has become an important technology in modern front-end development because it helps developers build interactive user interfaces using reusable components. Developed by Meta, React allows developers to organise complex interfaces into smaller, manageable parts and update the user interface efficiently when application data changes.

For freshers entering the software development industry, understanding React.js can create opportunities in front-end development, UI development, and full-stack JavaScript roles. However, interviewers usually expect more than basic definitions. They may ask candidates to explain component lifecycle behaviour, compare props and state, demonstrate React Hooks, or build a small application during a technical round.

Preparing with relevant React.js Interview Questions and Answers for Freshers helps candidates understand the concepts recruiters commonly evaluate and practise explaining them with confidence.

This guide covers beginner-friendly questions, practical coding examples, React Hooks, advanced concepts, and technical interview preparation strategies.

Section 1: Basic React.js Interview Questions and Answers

1. What is React.js?

React.js is an open-source JavaScript library used to build user interfaces, particularly interactive web applications. It allows developers to create reusable UI components and manage changes in application data.

React follows a component-based approach, which makes large applications easier to organise, develop, and maintain.

2. Who developed React.js?

React was originally developed by Facebook, now known as Meta. It was created to help build dynamic user interfaces and was publicly released as an open-source project in 2013.

3. What are the main features of React.js?

React includes several features that support modern user interface development.

  • Component-based architecture: Applications are divided into reusable components.
  • JSX: Developers can describe UI structures using JavaScript syntax that resembles HTML.
  • Declarative rendering: Developers describe the desired UI for a given state, and React manages the updates.
  • One-way data flow: Data generally flows from parent components to child components through props.
  • Hooks: Functional components can use state and other React features through Hooks.
  • Efficient updates: React uses reconciliation to determine the necessary changes to the rendered UI.

4. What is a React component?

A React component is a reusable piece of a user interface. It can contain markup, logic, and styling-related behaviour.

React components are commonly written as JavaScript functions.

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

export default Welcome;

The Welcome component can be reused wherever the application needs to display the same interface.

5. What is JSX in React?

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

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

    return <h1>Hello, {name}!</h1>;
}

JSX makes UI structures easier to read and write. Build tools transform JSX into JavaScript that React can use.

6. Is JSX mandatory in React?

No. JSX is not mandatory, but it is widely used because it makes component structures easier to understand.

React also provides APIs such as createElement() for creating React elements without JSX.

import { createElement } from "react";

const heading = createElement("h1", null, "Hello React");

7. What is the difference between React and JavaScript?

JavaScript is a programming language used for web development and many other applications. React is a JavaScript library that provides tools and patterns for building user interfaces.

JavaScript React
It is a programming language. It is a JavaScript UI library.
Supports general programming logic. Focuses on building user interfaces.
Can manipulate the DOM directly. Uses a declarative rendering model.
Does not require a component model. Encourages component-based development.

8. What is the Virtual DOM in React?

The Virtual DOM is a commonly used term for the in-memory representation of the UI that React uses during rendering.

When component data changes, React calculates what needs to change in the rendered interface and commits the necessary updates to the browser DOM.

This process helps developers work with UI updates declaratively rather than manually managing every DOM change.

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

The browser DOM represents the actual document displayed by the browser. React works with its own element and rendering model to calculate updates before committing changes to the DOM.

Virtual DOM concept Browser DOM
Represents UI elements in React's rendering process. Represents the actual document structure.
Used by React to calculate UI updates. Used by the browser to display and interact with the page.
Updated as part of React rendering. Receives committed changes from React.
Not directly displayed to users. Determines the rendered webpage.

10. What is a single-page application (SPA)?

A single-page application is a web application that loads an initial HTML document and updates its content dynamically as users interact with it.

React is commonly used to develop SPAs because its component-based architecture supports interactive interfaces without requiring a full document reload for every navigation.

11. What is the difference between functional and class components?

Functional components are JavaScript functions that return React elements. Class components are ES6 classes that extend React.Component and implement a render() method.

Functional Components Class Components
Defined using JavaScript functions. Defined using JavaScript classes.
Use Hooks for state and effects. Use lifecycle methods and class state.
Generally require less boilerplate. Often contain more boilerplate.
Recommended for most new React development. Still supported, especially in existing applications.

Example of a functional component:

function Greeting() {
    return <h2>Hello Developer</h2>;
}

Example of a class component:

import React from "react";

class Greeting extends React.Component {
    render() {
        return <h2>Hello Developer</h2>;
    }
}

12. What is the purpose of the render() method?

In class components, the render() method describes the UI that the component should display. It returns React elements, usually written using JSX.

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

Functional components return their UI directly instead of using a render() method.

13. What are props in React?

Props, short for properties, are inputs passed from a parent component to a child component. They allow components to receive data and customise their output.

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

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

Here, name is passed from App to User through props.

14. What is state in React?

State is data managed by a component that can change over time. When state is updated through the appropriate React API, React schedules a re-render so the interface can reflect the new value.

import { useState } from "react";

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

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

15. What is the difference between props and state?

Props and state are both used to manage component data, but they serve different purposes.

Props State
Passed into a component by its parent. Managed by the component or its owner.
Read-only from the receiving component's perspective. Updated using React state APIs.
Used to customise child components. Used to manage changing application data.
Supports parent-to-child data flow. Can trigger a component re-render when updated.

16. What is one-way data binding in React?

React generally follows a one-way data flow model in which parent components pass data to child components through props.

When a child needs to communicate a change to its parent, the parent can pass a callback function that the child invokes.

This approach makes data flow easier to understand and debug.

17. What is conditional rendering in React?

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

function LoginStatus({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn ? (
                <h2>Welcome Back!</h2>
            ) : (
                <h2>Please Log In</h2>
            )}
        </div>
    );
}

React supports conditional rendering through JavaScript conditions, ternary operators, and logical operators.

18. How do you render a list in React?

React commonly uses JavaScript's map() method to render lists of elements.

function Courses() {
    const courses = ["HTML", "CSS", "React"];

    return (
        <ul>
            {courses.map((course) => (
                <li key={course}>{course}</li>
            ))}
        </ul>
    );
}

The key helps React identify items when a list changes.

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

The key prop gives each element in a rendered collection a stable identity. React uses keys to match items between renders when elements are added, removed, or reordered.

const users = [
    { id: 1, name: "Arun" },
    { id: 2, name: "Priya" }
];

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

Stable IDs are generally preferable to array indexes when the list can change.

20. What is the difference between controlled and uncontrolled components?

Controlled form elements have their values managed by React state. Uncontrolled form elements maintain their values in the DOM, and developers can access them through references or form APIs.

Controlled component:

import { useState } from "react";

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

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

Uncontrolled component:

import { useRef } from "react";

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

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

    return (
        <form onSubmit={handleSubmit}>
            <input ref={inputRef} />
            <button type="submit">Submit</button>
        </form>
    );
}

Controlled components are useful when form values must be validated or used to update the UI as the user types.

Section 2: React.js Interview Questions for Freshers

21. What is the purpose of useState()?

useState() is a React Hook that allows functional components to manage state.

It returns the current state value and a setter function that can update that value.

import { useState } from "react";

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

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

22. What is the purpose of useEffect()?

useEffect() is a React Hook used to synchronise a component with external systems, such as browser APIs, subscriptions, and network connections.

import { useEffect, useState } from "react";

function Example() {
    const [message, setMessage] = useState("Loading");

    useEffect(() => {
        document.title = message;
    }, [message]);

    return (
        <button onClick={() => setMessage("React Updated")}>
            Update Title
        </button>
    );
}

The dependency array determines when the Effect needs to re-synchronise.

23. What is the purpose of useContext()?

useContext() allows a component to read values from a React context without passing props through every intermediate component.

It is useful for sharing information such as themes, authentication details, or application settings.

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

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

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

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

24. What is the purpose of useRef()?

useRef() creates a mutable reference that persists between renders without causing a re-render when its value changes.

It is commonly used to access DOM elements or store values that do not need to appear in the UI.

import { useRef } from "react";

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

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

    return (
        <>
            <input ref={inputRef} />
            <button onClick={focusInput}>Focus Input</button>
        </>
    );
}

25. What is the purpose of useMemo()?

useMemo() caches the result of a calculation between renders while its dependencies remain unchanged.

It can help avoid expensive recalculations when performance measurements show that the calculation is a bottleneck.

import { useMemo, useState } from "react";

function ProductList({ products }) {
    const [search, setSearch] = useState("");

    const filteredProducts = useMemo(() => {
        return products.filter((product) =>
            product.name.toLowerCase().includes(search.toLowerCase())
        );
    }, [products, search]);

    return (
        <>
            <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Search products"
            />

            {filteredProducts.map((product) => (
                <p key={product.id}>{product.name}</p>
            ))}
        </>
    );
}

26. What is the purpose of useCallback()?

useCallback() caches a function definition between renders while its dependencies remain unchanged.

It can be useful when passing callbacks to memoised child components or when a stable function reference is needed by another Hook.

import { useCallback, useState } from "react";

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

    const increment = useCallback(() => {
        setCount((previous) => previous + 1);
    }, []);

    return <button onClick={increment}>{count}</button>;
}

27. What is the difference between useMemo() and useCallback()?

Both Hooks help preserve values between renders, but they serve different purposes.

useMemo() useCallback()
Caches the result of a calculation. Caches a function definition.
Useful for expensive derived values. Useful for stable callback references.
Returns a memoised value. Returns a memoised function.

28. What are React Hooks?

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

Common Hooks include:

  • useState() manages component state.
  • useEffect() synchronises with external systems.
  • useContext() reads context values.
  • useRef() stores mutable references.
  • useMemo() caches calculation results.
  • useCallback() caches function definitions.
  • useReducer() manages state using a reducer function.
  • useLayoutEffect() performs layout-related synchronisation before the browser repaints.

29. What are the Rules of Hooks?

React Hooks follow specific rules to ensure that React can track Hook calls consistently.

  • Call Hooks only at the top level of a function component or custom Hook.
  • Do not call Hooks inside loops, conditions, or nested functions.
  • Call Hooks from React function components or custom Hooks, not ordinary JavaScript functions.
  • Keep Hook calls in the same order on every render.

Following these rules helps React associate state and other Hook data with the correct component.

30. What is a custom Hook in React?

A custom Hook is a reusable JavaScript function that uses React Hooks to share stateful logic between components.

Custom Hook names should begin with use.

import { useState } from "react";

function useToggle(initialValue = false) {
    const [value, setValue] = useState(initialValue);

    function toggle() {
        setValue((previous) => !previous);
    }

    return [value, toggle];
}

function ToggleButton() {
    const [isOn, toggle] = useToggle();

    return (
        <button onClick={toggle}>
            {isOn ? "ON" : "OFF"}
        </button>
    );
}

31. What is the purpose of useReducer()?

useReducer() is a Hook used to manage state through a reducer function. It is useful when state updates involve multiple actions or more complex transitions.

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

    return (
        <>
            <h2>{state.count}</h2>
            <button onClick={() => dispatch({ type: "increment" })}>
                Increase
            </button>
            <button onClick={() => dispatch({ type: "decrement" })}>
                Decrease
            </button>
        </>
    );
}

32. What is the difference between useEffect() and useLayoutEffect()?

Both Hooks synchronise a component with external systems, but they run at different points in the rendering process.

useEffect() useLayoutEffect()
Generally runs after the browser has had an opportunity to paint. Runs after DOM mutations but before the browser repaints.
Suitable for many subscriptions and network-related synchronisations. Suitable for layout measurement and visual adjustments that must happen before paint.
Usually preferred for ordinary Effects. Can block painting, so it should be used only when necessary.

33. What is prop drilling in React?

Prop drilling occurs when data is passed through multiple intermediate components even though those components do not directly need it.

For example, a parent may pass user information through several levels before it reaches a deeply nested profile component.

Context or a suitable state management approach can reduce unnecessary prop drilling.

34. What is React Context API?

The Context API allows components to share values across a component tree without manually passing props through every level.

It is suitable for values such as themes, user preferences, and authentication information.

35. What is React Fragment?

A React Fragment allows developers to group multiple elements without adding an extra DOM element.

function App() {
    return (
        <>
            <h1>Welcome</h1>
            <p>Learn React development.</p>
        </>
    );
}

Fragments help keep the rendered DOM structure clean.

36. What is event handling in React?

Event handling allows React components to respond to user interactions such as clicks, typing, form submissions, and keyboard input.

function Button() {
    function handleClick() {
        alert("Button clicked!");
    }

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

React event handlers use camelCase names such as onClick and onChange.

37. What is the difference between onClick and onclick in React?

React uses camelCase event property names such as onClick. Lowercase onclick is not the standard React JSX event prop.

<button onClick={() => alert("Hello")}>
    Click
</button>

38. What is the purpose of preventDefault()?

preventDefault() is a browser event method that prevents the browser's default action for an event when that action is cancelable.

It is commonly used to prevent a form from performing its default navigation during a client-side submission.

function Form() {
    function handleSubmit(event) {
        event.preventDefault();
        console.log("Form submitted");
    }

    return (
        <form onSubmit={handleSubmit}>
            <button type="submit">Submit</button>
        </form>
    );
}

39. What is event bubbling?

Event bubbling is a browser event propagation process in which an event begins at its target and then travels through its ancestor elements.

React applications can use event bubbling to manage interactions at parent elements.

function App() {
    return (
        <div onClick={() => console.log("Parent clicked")}>
            <button
                onClick={(event) => {
                    event.stopPropagation();
                    console.log("Button clicked");
                }}
            >
                Click Me
            </button>
        </div>
    );
}

40. What is the purpose of React.memo()?

React.memo() is a higher-order component that can skip re-rendering a function component when its props are unchanged according to its comparison.

import { memo } from "react";

const UserCard = memo(function UserCard({ name }) {
    return <h2>{name}</h2>;
});

It can improve performance when a component renders frequently with the same props, but it should be used based on actual performance needs.

Section 3: React.js Technical Interview Questions

41. What is reconciliation in React?

Reconciliation is the process React uses to compare the previous rendered element structure with the next one and determine the updates needed to keep the UI in sync with application data.

React uses element types, keys, and other information to decide whether existing elements can be updated or need to be replaced.

42. What is React Fiber?

React Fiber is React's internal reconciliation architecture. It enables React to organise rendering work into units and supports scheduling features that help manage complex updates.

Developers generally do not interact with Fiber directly, but understanding its purpose can help explain how React manages rendering work.

43. What is the difference between rendering and committing in React?

Rendering is the phase in which React calls components and calculates the next UI. Committing is the phase in which React applies the necessary changes to the host environment, such as the browser DOM.

A component may render without causing a visible DOM change.

44. What is the difference between createRoot() and the older ReactDOM.render()?

Modern React applications use createRoot() from react-dom/client to create a root for rendering an application.

import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(document.getElementById("root"));

root.render(<App />);

ReactDOM.render() was used in older React versions and is no longer the recommended API for modern React applications.

45. What is React Strict Mode?

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

It can enable additional development checks, including extra component rendering and Effect setup-cleanup cycles in relevant configurations. These checks help developers identify impure rendering and missing cleanup logic.

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

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

46. What are synthetic events in React?

React events provide a consistent event interface across supported browsers. Modern React uses the browser's native event system with React's event handling layer rather than relying on a separate pooled event system.

Developers can access common event properties and methods through event handler arguments.

47. What is lazy loading in React?

Lazy loading allows an application to load certain components only when they are needed. It can reduce the initial JavaScript bundle size.

React supports lazy component loading through lazy() and Suspense.

import { lazy, Suspense } from "react";

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

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

48. What is the purpose of Suspense in React?

Suspense displays fallback content while its child components are waiting for a supported resource or lazy-loaded component.

import { Suspense, lazy } from "react";

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

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

Suspense can also be used with supported data-fetching frameworks and libraries.

49. What are error boundaries in React?

Error boundaries are React components that catch rendering errors in their descendant component tree and display a fallback interface.

They are traditionally implemented using class components with lifecycle methods such as getDerivedStateFromError() and componentDidCatch().

import React from "react";

class ErrorBoundary extends React.Component {
    state = { hasError: false };

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

    componentDidCatch(error, info) {
        console.error(error, info);
    }

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

        return this.props.children;
    }
}

Error boundaries do not automatically catch every error, such as errors in event handlers or asynchronous callbacks.

50. What is the purpose of React Router?

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

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

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

The exact import paths and APIs depend on the React Router version and the routing setup used by the project.

51. What is the difference between client-side and server-side rendering?

Client-side rendering builds or updates much of the interface in the browser using JavaScript. Server-side rendering generates HTML on the server and sends it to the browser before client-side hydration.

Client-Side Rendering Server-Side Rendering
UI is primarily rendered in the browser. Initial HTML is generated on the server.
Requires JavaScript to build much of the initial UI. Can deliver meaningful initial HTML before hydration.
Common in traditional React SPA setups. Common in React frameworks that support server rendering.
May require additional work for initial loading and SEO. Can improve initial content availability when implemented correctly.

52. What is hydration in React?

Hydration is the process of attaching React's client-side behaviour to HTML that was already rendered on the server.

It allows server-generated markup to become interactive in the browser without recreating the entire document from scratch.

53. What is the difference between useTransition() and useDeferredValue()?

Both Hooks help manage non-urgent UI updates, but they work differently.

useTransition() allows developers to mark certain state updates as non-urgent transitions.

useDeferredValue() allows a part of the UI to use a deferred version of a value while a more urgent update is processed.

They are useful for keeping interfaces responsive during expensive rendering work.

54. What is the purpose of useId()?

useId() generates stable IDs that can be used to connect related accessibility attributes, such as labels and input controls.

import { useId } from "react";

function EmailField() {
    const id = useId();

    return (
        <>
            <label htmlFor={id}>Email Address</label>
            <input id={id} type="email" />
        </>
    );
}

It is not intended to generate list keys.

55. What is the purpose of useImperativeHandle()?

useImperativeHandle() allows a component to customise the value exposed through a ref.

It is useful when a parent component needs access to a limited set of imperative actions from a child component.

import { useImperativeHandle, useRef } from "react";

function CustomInput({ ref }) {
    const inputRef = useRef(null);

    useImperativeHandle(ref, () => ({
        focus() {
            inputRef.current.focus();
        }
    }));

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

This example uses the React 19 ref-as-prop approach. In earlier React versions, forwardRef() is commonly used to receive a ref from a parent.

56. What is the difference between useEffect() and an event handler?

An event handler responds to a specific user action, such as a click or form submission. An Effect synchronises a component with an external system after rendering.

For example, submitting a form belongs in an event handler, while subscribing to an external data source generally belongs in an Effect.

57. What is state lifting in React?

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

It helps maintain a single source of truth when multiple components depend on the same data.

58. What is the difference between defaultProps and default parameter values?

Default parameter values are a JavaScript feature used to provide fallback values when a function argument is missing or undefined.

function Welcome({ name = "Guest" }) {
    return <h2>Welcome, {name}</h2>;
}

For function components, default parameter values are a straightforward way to define fallback prop values.

59. What is the purpose of portals in React?

React portals allow components to render their children into a DOM node outside their normal parent DOM hierarchy while remaining part of the same React tree.

They are commonly used for modals, tooltips, and overlays.

import { createPortal } from "react-dom";

function Modal() {
    return createPortal(
        <div className="modal">Welcome to the application</div>,
        document.getElementById("modal-root")
    );
}

60. What is the difference between a React element and a React component?

A React component is a function or class that describes how a part of the UI should be rendered. A React element is the object-like description of a particular UI node produced by JSX or React APIs.

For example, Welcome is a component, while <Welcome /> creates a React element describing its use.

Section 4: React Hooks Interview Questions

61. Why were React Hooks introduced?

Hooks were introduced to allow functional components to use state, lifecycle-related synchronisation, and other React capabilities without relying on class components.

They also make it easier to reuse stateful logic through custom Hooks.

62. Can we use Hooks inside class components?

No. React Hooks can only be called from function components or custom Hooks. Class components use class state and lifecycle methods instead.

63. Can we call a Hook conditionally?

No. Hooks should not be called conditionally because React relies on a consistent order of Hook calls across renders.

Incorrect example:

if (isLoggedIn) {
    const [user, setUser] = useState(null);
}

Correct approach:

const [user, setUser] = useState(null);

if (!isLoggedIn) {
    return <p>Please log in.</p>;
}

64. What happens when the dependency array of useEffect() is empty?

An Effect with an empty dependency array is intended to run its setup after the component's initial commit and not re-run because of ordinary prop or state changes.

In development Strict Mode, React may perform an additional setup-cleanup cycle to help identify problems.

useEffect(() => {
    console.log("Effect setup");

    return () => {
        console.log("Effect cleanup");
    };
}, []);

65. What happens if the dependency array is omitted from useEffect()?

When the dependency array is omitted, the Effect runs after every commit.

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

This can cause unnecessary work if the Effect performs expensive operations or updates state without appropriate conditions.

66. What is the cleanup function in useEffect()?

The cleanup function performs necessary cleanup before an Effect re-synchronises and when the component is removed.

It is commonly used to clear timers, remove event listeners, and unsubscribe from external services.

import { useEffect } from "react";

function WindowWidth() {
    useEffect(() => {
        function handleResize() {
            console.log(window.innerWidth);
        }

        window.addEventListener("resize", handleResize);

        return () => {
            window.removeEventListener("resize", handleResize);
        };
    }, []);

    return <p>Resize the browser window.</p>;
}

67. What is the difference between useRef() and useState()?

useRef() useState()
Stores a mutable reference. Stores component state.
Updating .current does not trigger a re-render. Updating state schedules a re-render.
Useful for DOM access and persistent mutable values. Useful for data displayed in the UI.
Changes do not automatically update the rendered interface. New state is reflected in the rendered interface.

68. What is the purpose of useSyncExternalStore()?

useSyncExternalStore() allows a component to subscribe to an external store and read its current snapshot in a way that is compatible with React's rendering model.

It is useful for integrating external state management libraries or browser-backed stores.

69. What is the purpose of useInsertionEffect()?

useInsertionEffect() is a specialised Hook mainly intended for CSS-in-JS library authors who need to insert styles before layout Effects run.

Most application developers should prefer ordinary Effects or layout Effects where appropriate.

70. What is the difference between a custom Hook and a normal JavaScript function?

A normal JavaScript function performs reusable logic without necessarily using React features. A custom Hook can call other React Hooks to share stateful logic between components.

Custom Hooks must follow the Rules of Hooks and should use names beginning with use.

Section 5: Practical React.js Coding Interview Questions

Interviewers often use practical coding tasks to evaluate whether candidates can build components, manage state, and handle user interactions. The following examples demonstrate common interview exercises.

71. How do you create a counter application in React?

A counter application demonstrates state management and event handling.

import { useState } from "react";

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

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

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

            <button onClick={() => setCount((c) => c - 1)}>
                Decrease
            </button>

            <button onClick={() => setCount(0)}>
                Reset
            </button>
        </div>
    );
}

export default Counter;

72. How do you create a simple React form?

React forms commonly use controlled inputs to manage user-entered values through state.

import { useState } from "react";

function RegistrationForm() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");

    function handleSubmit(event) {
        event.preventDefault();

        console.log({ name, email });
    }

    return (
        <form onSubmit={handleSubmit}>
            <input
                type="text"
                placeholder="Enter name"
                value={name}
                onChange={(event) => setName(event.target.value)}
                required
            />

            <input
                type="email"
                placeholder="Enter email"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required
            />

            <button type="submit">Register</button>
        </form>
    );
}

73. How do you fetch API data in React?

An API request can be made inside an Effect when the component needs to synchronise with a remote data source.

import { useEffect, useState } from "react";

function Users() {
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState("");

    useEffect(() => {
        const controller = new AbortController();

        async function fetchUsers() {
            try {
                const response = await fetch(
                    "https://jsonplaceholder.typicode.com/users",
                    { signal: controller.signal }
                );

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

                const data = await response.json();
                setUsers(data);
            } catch (err) {
                if (err.name !== "AbortError") {
                    setError(err.message);
                }
            } finally {
                if (!controller.signal.aborted) {
                    setLoading(false);
                }
            }
        }

        fetchUsers();

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

    if (loading) return <p>Loading...</p>;
    if (error) return <p>{error}</p>;

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

This example includes loading, error, and successful data states, along with request cancellation during cleanup.

74. How do you implement search functionality in React?

Search functionality can be implemented by storing the search term in state and filtering a list of data.

import { useState } from "react";

function SearchProducts() {
    const [search, setSearch] = useState("");

    const products = [
        "Laptop",
        "Mobile",
        "Keyboard",
        "Monitor"
    ];

    const filteredProducts = products.filter((product) =>
        product.toLowerCase().includes(search.toLowerCase())
    );

    return (
        <div>
            <input
                type="text"
                placeholder="Search products"
                value={search}
                onChange={(event) => setSearch(event.target.value)}
            />

            {filteredProducts.map((product) => (
                <p key={product}>{product}</p>
            ))}
        </div>
    );
}

75. How do you implement show and hide functionality in React?

A Boolean state variable can control whether a particular element is displayed.

import { useState } from "react";

function ToggleContent() {
    const [show, setShow] = useState(false);

    return (
        <div>
            <button onClick={() => setShow((value) => !value)}>
                {show ? "Hide" : "Show"}
            </button>

            {show && <p>This content is now visible.</p>}
        </div>
    );
}

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

Data can be passed using props.

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

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

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

A parent can pass a callback function to a child. The child calls that function with the data it wants to send.

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

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

    return <Child onSend={handleMessage} />;
}

78. How do you create a reusable button component in React?

A reusable button accepts props for its label and behaviour.

function Button({ label, onClick, disabled = false }) {
    return (
        <button onClick={onClick} disabled={disabled}>
            {label}
        </button>
    );
}

function App() {
    return (
        <Button
            label="Submit"
            onClick={() => console.log("Submitted")}
        />
    );
}

Reusable components help maintain consistent behaviour and appearance across an application.

79. How do you implement a todo list in React?

A todo list demonstrates state updates, event handling, and list rendering.

import { useState } from "react";

function TodoList() {
    const [task, setTask] = useState("");
    const [tasks, setTasks] = useState([]);

    function addTask() {
        const value = task.trim();

        if (!value) return;

        setTasks((previous) => [
            ...previous,
            { id: crypto.randomUUID(), text: value }
        ]);

        setTask("");
    }

    return (
        <div>
            <input
                value={task}
                onChange={(event) => setTask(event.target.value)}
                placeholder="Enter a task"
            />

            <button onClick={addTask}>Add Task</button>

            <ul>
                {tasks.map((item) => (
                    <li key={item.id}>{item.text}</li>
                ))}
            </ul>
        </div>
    );
}

80. How do you implement pagination in React?

Pagination divides a large collection of records into smaller groups and displays one group at a time.

import { useState } from "react";

function Pagination({ items, pageSize = 5 }) {
    const [page, setPage] = useState(1);

    const totalPages = Math.ceil(items.length / pageSize);

    const start = (page - 1) * pageSize;
    const visibleItems = items.slice(start, start + pageSize);

    return (
        <div>
            {visibleItems.map((item) => (
                <p key={item.id}>{item.name}</p>
            ))}

            <button
                disabled={page === 1}
                onClick={() => setPage((p) => p - 1)}
            >
                Previous
            </button>

            <span> Page {page} of {totalPages} </span>

            <button
                disabled={page === totalPages || totalPages === 0}
                onClick={() => setPage((p) => p + 1)}
            >
                Next
            </button>
        </div>
    );
}

Section 6: Advanced React.js Interview Questions

81. What is the difference between useTransition() and normal state updates?

Normal state updates are generally treated as urgent unless they are part of a transition. useTransition() allows developers to mark certain updates as non-urgent so React can keep more important interactions responsive.

import { useState, useTransition } from "react";

function Search() {
    const [query, setQuery] = useState("");
    const [results, setResults] = useState([]);
    const [isPending, startTransition] = useTransition();

    function handleChange(event) {
        const value = event.target.value;

        setQuery(value);

        startTransition(() => {
            setResults(
                Array.from({ length: 1000 }, (_, index) => ({
                    id: index,
                    name: `${value} Result ${index + 1}`
                }))
            );
        });
    }

    return (
        <>
            <input value={query} onChange={handleChange} />

            {isPending && <p>Updating results...</p>}

            {results.slice(0, 10).map((item) => (
                <p key={item.id}>{item.name}</p>
            ))}
        </>
    );
}

82. What is automatic batching in React?

Automatic batching allows React to group multiple state updates into fewer renders in supported React configurations.

This helps reduce unnecessary rendering work when several state updates occur during the same event or supported asynchronous operation.

83. What is the difference between useDeferredValue() and debouncing?

useDeferredValue() allows React to defer updating part of the UI so urgent interactions can remain responsive. Debouncing delays the execution of a function until a specified period has passed without another call.

useDeferredValue() Debouncing
A React Hook for deferring a UI value. A general programming technique.
Helps prioritise rendering work. Reduces how frequently a function executes.
Does not guarantee a fixed time delay. Commonly uses a configured delay.
Useful for expensive UI updates. Useful for search requests and repeated input events.

84. What is concurrent rendering in React?

Concurrent rendering describes React's ability to prepare and manage rendering work in an interruptible manner, allowing urgent updates to receive priority over less important work.

It supports features such as transitions and helps React manage complex interfaces more responsively.

85. What is server-side rendering in modern React applications?

Server-side rendering generates the initial HTML on the server before sending it to the browser. React frameworks can combine server rendering with client-side hydration to create interactive applications.

This approach can improve initial content delivery and support search engine accessibility when correctly implemented.

86. What are React Server Components?

React Server Components are components that render on the server and are not included in the client-side JavaScript bundle in the same way as client components.

They can access server-side resources and help reduce the amount of JavaScript sent to the browser. Their usage depends on a framework or environment that supports the React Server Components architecture.

87. What is the difference between Server Components and Client Components?

Server Components Client Components
Render on the server. Support client-side interactivity.
Can access server-side resources within supported environments. Can use browser APIs and interactive Hooks.
Do not add their component implementation to the client bundle in the same way as Client Components. Their code is delivered to the client.
Cannot use client-only Hooks such as useState() and useEffect(). Can use state and Effect Hooks.

The exact boundaries and syntax depend on the framework being used.

88. What is code splitting in React?

Code splitting divides an application's JavaScript into smaller bundles that can be loaded when required.

React's lazy() function and dynamic imports are commonly used to load components on demand.

import { lazy, Suspense } from "react";

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

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

89. How can you optimise the performance of a React application?

React performance can be improved by reducing unnecessary renders, managing state appropriately, splitting code, and optimising expensive calculations.

Useful techniques include:

  • Use stable keys when rendering dynamic lists.
  • Keep state close to the components that need it.
  • Use React.memo() when memoisation provides a measurable benefit.
  • Apply useMemo() for expensive calculations when appropriate.
  • Use useCallback() when stable function references are beneficial.
  • Lazy-load large components and routes.
  • Avoid unnecessary Effects and repeated state updates.
  • Profile rendering using React Developer Tools.
  • Optimise images, fonts, and other external resources.
  • Use virtualisation for very large lists when necessary.

90. What is the difference between Redux and Context API?

Both can help share data across components, but they solve different state management needs.

Context API Redux
Built into React. A separate state management ecosystem.
Useful for sharing values across a component tree. Useful for managing more complex application-wide state.
Does not provide a complete state management architecture by itself. Provides structured patterns for state updates and debugging.
Often suitable for themes and user settings. Often suitable for applications with complex shared state.

Context is not automatically a replacement for every state management requirement. The right choice depends on application complexity.

Section 7: Practical Strategy to Prepare for React.js Interviews

A strong interview preparation plan should combine theoretical knowledge, coding practice, and the ability to explain development decisions.

1. Understand JavaScript Fundamentals First

React is built around JavaScript, so candidates should understand variables, functions, arrays, objects, arrow functions, destructuring, modules, promises, and asynchronous programming.

Without these fundamentals, understanding JSX, Hooks, props, and state becomes more difficult.

2. Master Components, Props, and State

Practise creating reusable functional components and passing data through props. Understand how state changes affect the UI and why React components should avoid directly mutating state.

3. Practise React Hooks

Learn the purpose and practical usage of useState(), useEffect(), useContext(), useRef(), useMemo(), useCallback(), and useReducer().

Candidates should be able to explain when a Hook is useful and identify situations where using it is unnecessary.

4. Build Small React Projects

Create practical projects such as a todo application, product search page, registration form, weather interface, and API-powered user list.

These projects demonstrate how different React concepts work together in an application.

5. Learn API Integration

Practise using fetch() or a suitable HTTP client to retrieve data from APIs. Understand loading states, error handling, request cancellation, and displaying dynamic data.

6. Understand Routing and State Management

Learn how routing libraries manage navigation and how shared application data can be organised through Context, reducers, or dedicated state management libraries.

7. Practise Explaining Your Code

During technical interviews, explain your component structure, state decisions, data flow, and performance considerations. Interviewers often value clear problem-solving approaches as much as the final code.

Candidates looking for structured web development learning and interview preparation can explore relevant training opportunities at Well Spring Talent Solutions.

React.js Interview Preparation Checklist

Use this checklist to evaluate your readiness before attending a React.js technical interview.

  • Explain React.js and its component-based architecture.
  • Understand JSX, React elements, and functional components.
  • Explain props, state, and one-way data flow.
  • Understand conditional rendering and list rendering.
  • Use stable keys when rendering dynamic lists.
  • Build controlled forms and handle user events.
  • Understand the Rules of Hooks.
  • Practise useState(), useEffect(), and useContext().
  • Understand useRef(), useMemo(), and useCallback().
  • Build custom Hooks and reusable components.
  • Fetch API data and manage loading and error states.
  • Understand React Router and application navigation.
  • Learn component rendering, reconciliation, and hydration.
  • Understand lazy loading, Suspense, and code splitting.
  • Practise performance optimisation and debugging.
  • Build at least two small React projects independently.

Conclusion

React.js is an important skill for developers who want to build modern, interactive web applications. A strong understanding of components, JSX, props, state, Hooks, and event handling provides the foundation needed to work with React confidently.

For freshers, the most effective preparation approach is to learn the fundamentals first, practise practical coding exercises, and gradually move towards advanced topics such as reconciliation, routing, performance optimisation, and modern rendering techniques.

These React.js interview questions and answers for freshers provide a structured resource for revising important concepts and understanding the types of technical problems candidates may encounter. Consistent practice and the ability to explain code clearly can help candidates prepare more effectively for front-end development opportunities.

Frequently Asked Questions 

1. What are the most important React interview questions for freshers?

Freshers should prepare questions about React components, JSX, props, state, conditional rendering, list rendering, event handling, Hooks, and component reusability. They should also practise simple applications such as counters, forms, and todo lists.

2. Is React.js difficult to learn for beginners?

React.js becomes easier to understand when beginners have a basic knowledge of JavaScript, HTML, and CSS. Learning components, props, state, and Hooks step by step helps build a strong foundation.

3. Which React Hooks should freshers learn first?

Freshers should begin with useState() and useEffect(), followed by useContext() and useRef(). They can then learn useMemo(), useCallback(), and useReducer() to understand more advanced state and performance patterns.

4. What coding questions are asked in React.js interviews?

Common practical questions include creating a counter, building a todo application, handling form inputs, fetching API data, implementing search functionality, passing data between components, and displaying lists with unique keys.

5. Is JavaScript required before learning React.js?

Yes. A good understanding of JavaScript is important because React uses JavaScript concepts such as functions, arrays, objects, arrow functions, destructuring, promises, and modules.

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

React is primarily used to build web user interfaces, while React Native is used to build native mobile applications using React concepts. React Native renders native platform components rather than standard HTML elements.

7. How can freshers improve their chances of getting a React.js developer job?

Freshers can improve their preparation by strengthening JavaScript fundamentals, practising React Hooks, building practical projects, learning API integration, understanding responsive design, and maintaining a portfolio that demonstrates their development skills.

Back to Interview Questions
YOUR CAREER STARTS HERE

Ready to Prepare for Your Software Developer Interview?

Strengthen your programming fundamentals, practise technical interview questions, and build confidence for your next software developer interview with guidance from Well Spring Talent Solutions.

Learn Today. Build Tomorrow. Succeed for Life.

Your Local Destination for IT Training

We provide IT training, internships, and online learning for students in Trichy and across India.

IT Training Areas in Trichy

Thillai Nagar KK Nagar Srirangam Cantonment Woraiyur Tennur Karumandapam Edamalaipatti Pudur Puthur Crawford BHEL Township Ariyamangalam Kattur Ponmalai (Golden Rock) Vayalur Road Bharathidasan Salai Chathiram Bus Stand Palakkarai Subramaniapuram Sangiliyandapuram Trichy Airport Area Thiruverumbur Samayapuram Manachanallur Panjappur Navalpattu Central Bus Stand Trichy Railway Junction Gandhi Market Palpannai Anna Nagar Thiruvanaikoil TVS Tollgate Ponnagar Beemanagar Kallukuzhi Thuvakudi Pudukottai Road Thanjavur Road Karur Bypass Road

Online IT Training Across India

Can't attend classes in person? Explore online IT training opportunities with Well Spring Talent Solutions, designed to help learners develop practical technology skills from different locations across India.

Join Our WhatsApp Channel ๐Ÿ’ฌ

Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.

Join Now

Our Branches

Visit our branches in Tiruchirappalli for IT training and career guidance.