React JS Basic
Interview Questions with Answers

1. What is React, and why is it called a library instead of a framework?

Answer:
React is an open-source JavaScript library used for building user interfaces, especially single-page applications where the UI updates dynamically without reloading the whole page.

It is called a library instead of a framework because React mainly focuses only on the view layer (UI) of an application. Unlike frameworks that provide a complete structure with routing, state management, and form handling, React allows developers to pick and integrate other tools or libraries for those needs. This flexibility makes React lightweight and adaptable.

Example:
If you want routing, React doesn’t provide it out of the box—you add React Router. If you want global state management, you add Redux or Context API. This is why React is considered a UI library, not a full framework.

Your career growth starts with the right step. Don’t wait—take action today!

2. Who developed React, and when was it first released?

Answer:
React was developed by Jordan Walke, a software engineer at Facebook. It was first released in May 2013 to the public. Initially, Facebook used it for its News Feed and Instagram, and later it became popular worldwide for building modern web applications.

Example:
Today, companies like Facebook, Instagram, Netflix, and Airbnb use React in their products.

3. What are the key advantages of using React?

Answer:
React offers several advantages that make it one of the most popular choices for front-end development:

  • Reusable Components – You build once and reuse across the app, saving time.
  • Virtual DOM – Updates only the necessary parts of the UI, making applications faster.
  • One-Way Data Flow – Makes code more predictable and easier to debug.
  • Strong Community Support – Backed by Meta and millions of developers.
  • Ecosystem – Works well with libraries like Redux, React Router, and Next.js.

Example:
In an e-commerce app, a ProductCard component can be reused to show hundreds of products without rewriting the UI logic each time.

4. What is the difference between React and plain JavaScript DOM manipulation?

Answer:

  • In plain JavaScript, developers manually select and update DOM elements using methods like document.getElementById() or document.querySelector(). This can become slow and messy when the application grows.
  • In React, the UI is built with a virtual DOM. React calculates the minimum changes needed and updates only those parts of the real DOM, making updates efficient and faster.

Example:

  • Plain JS:
document.getElementById("count").innerText = count;
  • React:
function Counter() {
const [count, setCount] = React.useState(0);
return <h1>{count}</h1>;
}

Here, React handles DOM updates automatically when count changes.

5. What is a Single Page Application (SPA), and how does React support it?

Answer:
A Single Page Application (SPA) is a type of web application that loads only once and then dynamically updates the content without refreshing the entire page.

React supports SPAs because it uses client-side rendering. With React Router, different components can be displayed for different URLs, but the browser doesn’t reload the page. Instead, React swaps components in and out, giving users a smooth experience.

Example:
When you visit /home or /about in a React app with React Router, the page doesn’t reload. Instead, React loads the Home or About component instantly.

6. What is a React component?

Answer:
A component is a reusable piece of UI in React. It is like a function that takes inputs (called props) and returns React elements (UI). Components help break down complex UIs into smaller, manageable parts.

Example:

function Button(props) {
return <button>{props.label}</button>;
}

Here, Button is a reusable component that can display different labels like “Login”, “Submit”, or “Register”.

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

Answer:

  • Functional Components:
    • Written as JavaScript functions.
    • Simpler, cleaner, and preferred in modern React.
    • Use hooks like useState and useEffect for state and lifecycle.
  • Class Components:
    • Written using ES6 classes.
    • Use this.state and lifecycle methods like componentDidMount.
    • Less common in modern React but still supported.

Example:

  • Functional:
function Welcome() {
return <h1>Hello React</h1>;
}
  • Class:
class Welcome extends React.Component {
render() {
   return <h1>Hello React</h1>;
}
}

8. What is the difference between presentational and container components?

Answer:

  • Presentational Components:
    • Focus on how things look.
    • Mostly receive data through props and display UI.
    • Don’t manage state or business logic.
  • Container Components:
    • Focus on how things work.
    • Handle state, logic, and data fetching.
    • Pass data down to presentational components.

Example:

  • Presentational:
function UserCard({ name }) {
return <h2>{name}</h2>;
}
  • Container:
function UserContainer() {
const [name, setName] = React.useState("John");
return <UserCard name={name} />;
}

9. What is a controlled component in React?

Answer:
A controlled component is a form input element whose value is controlled by React state. In other words, the input value is tied to the component’s state, and changes are handled by React.

Example:

function Form() {
const [text, setText] = React.useState("");
return (
   <input value={text} onChange={(e) => setText(e.target.value)} />
);
}

Here, the input value depends on the state text. React controls the input.

10. What is an uncontrolled component in React?

Answer:
An uncontrolled component is a form input element that maintains its own internal state, rather than relying on React state. You access the value using a ref.

Example:

function Form() {
const inputRef = React.useRef();
function handleSubmit() {
   alert(inputRef.current.value);
}
return (
   <>
     <input ref={inputRef} />
     <button onClick={handleSubmit}>Submit</button>
   </>
);
}

Here, the input value is not controlled by React state but accessed directly through the DOM.

11. What is JSX in React?

Answer:
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that looks very similar to HTML. JSX allows you to write UI components in a way that looks like HTML but actually compiles down to React.createElement() calls under the hood.

It makes the code more readable and declarative, allowing developers to see what the UI will look like directly inside JavaScript.

Example:

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

The above JSX is internally converted to:

const element = React.createElement("h1", null, "Hello, React!");

12. Can browsers understand JSX directly? Why or why not?

Answer:
No, browsers cannot understand JSX directly because browsers only understand plain JavaScript, not JSX syntax.

JSX must first be transpiled into JavaScript using tools like Babel before it runs in the browser.

Example:

const element = <p>JSX Example</p>; // Browser can't run this directly

After Babel transpilation:

const element = React.createElement("p", null, "JSX Example");

13. What is the difference between JSX and HTML?

Answer:
JSX looks like HTML but has some important differences:

  • In JSX, you use camelCase attributes (e.g., className instead of class).
  • JSX can embed JavaScript expressions inside curly braces {}.
  • JSX elements must have a single parent wrapper.
  • JSX is not a string or markup—it’s syntactic sugar for JavaScript function calls.

Example:

// JSX
<div className="container">
<h2>{2 + 2}</h2>
</div>

In HTML, you can’t write {2 + 2} to evaluate JavaScript.

14. How do you embed JavaScript expressions in JSX?

Answer:
You can embed JavaScript expressions inside JSX using curly braces {}. This allows you to dynamically display variables, functions, or calculations inside UI.

Example:

const name = "Learn2Earn Labs Training Institute";
const element = <h1>Welcome to, {name}!</h1>;

Here, {name} will be replaced with the string “Learn2Earn Labs Training Institute” when rendered.

15. Why must JSX elements be wrapped in a parent element?

Answer:
In JSX, every component must return a single root element because React uses the virtual DOM, and returning multiple sibling elements without a parent confuses the tree structure.

To solve this, we wrap multiple elements inside a parent element like <div> or <> (React Fragment).

Example:
Invalid JSX:

return (
<h1>Hello</h1>
<p>Welcome</p>
);

Valid JSX (using a parent wrapper):

return (
<>
   <h1>Hello</h1>
   <p>Welcome</p>
</>
);

16. What are props in React?

Answer:
Props (short for properties) are used to pass data from a parent component to a child component. They make components reusable by allowing dynamic values.

Props are immutable, meaning a child component cannot modify them.

Example:

function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
<Greeting name="Anjali" />

Here, “Anjali” is passed as a prop from the parent.

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

Answer:
You pass data from a parent to a child component by assigning attributes to the child component and then accessing them using props in the child.

Example:

function Child({ message }) {
return <p>{message}</p>;
}
function Parent() {
return <Child message="This is a message from Parent!" />;
}

Here, the parent sends message as a prop to the child.

18. What are default props in React?

Answer:
Default props are values that a component uses if no prop value is provided by the parent. This ensures components still work even if some props are missing.

Example:

function Button({ label }) {
return <button>{label}</button>;
}
Button.defaultProps = {
label: "Click Me"
};

If the parent doesn’t pass label, the button will display “Click Me”.

19. Are props read-only or mutable?

Answer:
Props are read-only. A child component cannot change the props it receives from its parent. This ensures that data always flows in one direction (top to bottom), making applications predictable.

Example:

function Display({ count }) {
// count = 10;  // Not allowed
return <p>Count is {count}</p>;
}

If you need to change values, use state instead of props.

20. How do you validate props in React using PropTypes?

Answer:
React provides a library called PropTypes to validate the type of props. It helps catch errors early by ensuring components receive props in the correct format.

Example:

import PropTypes from "prop-types";
function User({ name, age }) {
return <h2>{name} is {age} years old.</h2>;
}
User.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number
};

Here:

  • name must be a string and is required.
  • age must be a number but is optional.

Transform your skills into success. Enroll now and secure your future!

21. What is state in React?

Answer:
State in React is a built-in object that stores data specific to a component. It allows a component to remember information between renders and update the UI when data changes. Unlike props, which are passed from parent to child, state is managed within the component itself.

Example:

function Counter() {
const [count, setCount] = React.useState(0);
return <h1>{count}</h1>;
}

Here, count is the state, and setCount updates it.

22. How is state different from props?

Answer:

  • State is internal and managed by the component. It represents data that can change over time.
  • Props are external inputs passed to a component from its parent. They are read-only and cannot be changed by the child.

Example:

function Greeting({ name }) {  // name is a prop
const [message, setMessage] = React.useState("Hello"); // message is state
return <h1>{message}, {name}</h1>;
}

23. How do you update state in React?

Answer:
In functional components, state is updated using the state updater function from the useState hook. In class components, it’s updated using this.setState().

Example (functional):

function Counter() {
const [count, setCount] = React.useState(0);
return <button onClick={() => setCount(count + 1)}>Click {count}</button>;
}

24. What is the initial state, and how is it set?

Answer:
The initial state is the value you provide when the component is first rendered. In functional components, it is passed as an argument to useState(). In class components, it is defined inside the constructor.

Example (functional):

const [isLoggedIn, setIsLoggedIn] = React.useState(false);

Here, the initial state is false.

25. Why should you not modify state directly in React?

Answer:
You should never modify state directly because:

  1. React will not re-render the component if state is changed without setState() or setFunction.
  2. Direct modification can lead to unpredictable bugs and break the virtual DOM update cycle.

Example:
Wrong:

this.state.count = 5;  // No re-render

Correct:

this.setState({ count: 5 });

26. How do you handle events in React?

Answer:
Events in React are handled by adding event listeners as attributes to elements, using camelCase naming. The handler is a function that executes when the event occurs.

Example:

function Button() {
function handleClick() {
   alert("Button clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}

27. What is the difference between HTML events and React events?

Answer:

  • In HTML, events use lowercase (onclick, onchange).
  • In React, events use camelCase (onClick, onChange).
  • In HTML, event handlers can be strings (onclick=”doSomething()”).
  • In React, event handlers must be functions (onClick={doSomething}).
  • React events are wrapped in a SyntheticEvent object for cross-browser compatibility.

Example:

  • HTML: <button onclick="alert('Hi')">Click</button>
  • React: <button onClick={() => alert('Hi')}>Click</button>

28. How do you pass arguments to event handlers in React?

Answer:
You can pass arguments to an event handler by wrapping it in an arrow function.

Example:

function Greet({ name }) {
function sayHello(user) {
   alert("Hello, " + user);
}
return <button onClick={() => sayHello(name)}>Greet</button>;
}

Here, the prop name is passed as an argument.

29. How do you prevent the default behavior of an event in React?

Answer:
You can prevent the default behavior (like form submission or page reload) by calling event.preventDefault() inside the handler.

Example:

function Form() {
function handleSubmit(e) {
   e.preventDefault();
   alert("Form submitted without reload!");
}
return <form onSubmit={handleSubmit}><button>Submit</button></form>;
}

30. How do you use arrow functions in event handlers?

Answer:
Arrow functions are often used in React event handlers because they:

  1. Preserve this context automatically.
  2. Allow passing arguments directly.
  3. Keep code shorter and cleaner.

Example:

function Counter() {
const [count, setCount] = React.useState(0);
return (
   <button onClick={() => setCount(count + 1)}>
     Count: {count}
   </button>
);
}

Here, an arrow function updates the state directly in the event handler.

31. How do you render lists in React?

Answer:
In React, you render lists using JavaScript’s map() function. Each item in the list is transformed into a React element and returned inside JSX.

Example:

function Fruits() {
const fruits = ["Apple", "Banana", "Mango"];
return (
   <ul>
     {fruits.map((fruit, index) => (
       <li key={index}>{fruit}</li>
     ))}
   </ul>
);
}

This will render a list of fruit names.

32. What is the purpose of the key prop in React lists?

Answer:
The key prop helps React identify which items have changed, been added, or removed in a list. It improves performance by letting React update only the changed items instead of re-rendering the entire list.

Example:

<li key={fruit.id}>{fruit.name}</li>

Here, fruit.id uniquely identifies each item.

33. What happens if you don’t provide a key for list items?

Answer:
If you don’t provide a key:

  • React will rely on the index position by default.
  • This can cause performance issues and unexpected bugs (like incorrect reordering or stale state in list items).
  • React will also show a warning in the console.

34. Can keys be duplicated across elements in a list?

Answer:
No. Keys must be unique among siblings in a list. If keys are duplicated, React cannot correctly identify list items, which may cause incorrect updates or rendering issues.

Example:

Wrong:

<li key="1">Apple</li>
<li key="1">Banana</li>

Correct:

<li key="apple">Apple</li>
<li key="banana">Banana</li>

35. Where should you not use array indexes as keys?

Answer:
Avoid using array indexes as keys when:

  • The list items can be reordered.
  • Items can be added or removed.
  • The list is dynamic and changes frequently.

In such cases, using indexes can cause React to reuse elements incorrectly, leading to UI bugs.

You can use indexes only for static lists that never change.

36. How do you implement conditional rendering in React?

Answer:
Conditional rendering means showing different UI based on conditions. In React, you can use:

  • if/else
  • ternary operators
  • logical &&
  • returning null

Example (if/else):

function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
   return <h1>Welcome Back!</h1>;
} else {
   return <h1>Please Login</h1>;
}
}

37. How do you use the ternary operator for conditional rendering?

Answer:
The ternary operator is a shorthand way to render elements conditionally.

Example:

function Greeting({ isLoggedIn }) {
return (
   <h1>{isLoggedIn ? "Welcome Back!" : "Please Login"}</h1>
);
}

If isLoggedIn is true → “Welcome Back!”, else → “Please Login”.

38. How do you render nothing (null) from a component?

Answer:
You can return null from a component when you don’t want to render anything. React will skip rendering that component.

Example:

function Notification({ show }) {
if (!show) {
   return null;
}
return <p>You have a new message!</p>;
}

If show is false, nothing is rendered.

39. How do you implement short-circuit evaluation (&&) in React rendering?

Answer:
You can use the && operator to render content only if a condition is true.

Example:

function Cart({ items }) {
return (
   <div>
     <h2>Shopping Cart</h2>
     {items.length > 0 && <p>You have {items.length} items</p>}
   </div>
);
}

Here, the message is shown only if items.length > 0.

40. What is the difference between conditional rendering and dynamic rendering?

Answer:

  • Conditional Rendering: Deciding whether to render a component or not (or which one to render) based on a condition.
    • Example: Showing “Login” vs “Logout” button.
  • Dynamic Rendering: Rendering different content dynamically based on data or user input, but the component itself is always rendered.

Example:

Displaying a list of products fetched from an API.

Example difference:

// Conditional Rendering
{isLoggedIn ? <Dashboard /> : <LoginForm />}
// Dynamic Rendering
{products.map(product => <ProductCard key={product.id} {...product} />)}

Every expert was once a beginner. Start your journey to excellence today!

41. What are React hooks?

Answer:
Hooks are special functions that let you use React features (state, lifecycle, context, refs, etc.) in function components. They remove the need for class components for most use cases and make logic easier to share via custom hooks.

Example:

import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // using a hook in a function component
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

42. What is the purpose of the useState hook?

Answer:
useState lets a function component remember values between renders and trigger re-renders when those values change. It returns the current state and a setter function.

Example:

const [name, setName] = useState("Guest");
// update:
setName("Anjali"); // UI re-renders with the new name

Key notes:

  • You can pass a function to the setter when the new value depends on the previous one:
    setCount(prev => prev + 1);
  • The initial value is used only on the first render.

43. What is the purpose of the useEffect hook?

Answer:
useEffect lets you run side effects after rendering—things like data fetching, subscriptions, timers, logging, or manually changing the DOM. You can also clean up effects to avoid memory leaks.

Example (fetch + cleanup):

import { useEffect, useState } from "react";
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
   let cancelled = false;
   fetch("/api/users")
     .then(r => r.json())
     .then(data => { if (!cancelled) setUsers(data); });
   return () => { cancelled = true; }; // cleanup
}, []); // run once on mount
return <div>Loaded: {users.length}</div>;
}

Dependency array rules:

  • [] → run once on mount.
  • [x, y] → re-run when x or y changes.
  • Omit it → run after every render.

44. What are the rules of hooks in React?

Answer:

  1. Only call hooks at the top level of your function component or custom hook (not inside loops, conditions, or nested functions).
  2. Only call hooks from React functions — function components or custom hooks (not from regular JS functions or class methods).

These rules ensure React calls hooks in the same order every render.

45. Can you use hooks inside class components?

Answer:
No. Hooks work only in function components (and custom hooks). In class components, you use state (this.state, this.setState) and lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount) instead.

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

Answer:

  • A React element is a plain object that describes what you want to see on the screen (like <div />). Elements are immutable snapshots created by React.createElement.
  • A React component is a function or class that returns elements. Components can have logic, state, and props.

Example:

// Element:
const el = <h1>Hello</h1>; // description of UI
// Component:
function Title() {
return <h1>Hello</h1>;  // returns an element
}

47. What is the Virtual DOM in React?

Answer:
The Virtual DOM is a lightweight in-memory representation of the real DOM. When state changes, React:

  1. Builds a new virtual tree,
  2. Diffs it with the previous tree,
  3. Updates only the necessary parts of the real DOM.

This makes updates fast and efficient compared to manual DOM manipulation.

Example idea: Updating a single item in a list causes React to patch just that node, not re-render the whole list’s DOM.

48. What are fragments in React, and why are they used?

Answer:
Fragments let you group multiple elements without adding an extra wrapper element to the DOM. They keep your markup clean and avoid unnecessary <div>s that can break layouts or CSS.

Syntax options:

<>                      {/* short syntax, no attributes */}
<li>A</li>
<li>B</li>
</>
<React.Fragment>        {/* long syntax, allows keys */}
<li>A</li>
<li>B</li>
</React.Fragment>

49. What is the purpose of React keys in fragments?

Answer:
When you return a list of fragments, each item still needs a unique key so React can track insertions, removals, and moves. You can only add a key to the long fragment form (<React.Fragment key={…}>), not to the short <>…</> syntax.

Example (mapping with keyed fragments):

const rows = data.map(item => (
<React.Fragment key={item.id}>
   <dt>{item.term}</dt>
   <dd>{item.definition}</dd>
</React.Fragment>
));

50. How do you apply inline styles in React?

Answer:
Use the style prop with a JavaScript object. Property names are camelCased, and values are usually strings or numbers (numbers imply px for many properties).

Example:

function Card() {
const box = { padding: 16, backgroundColor: "#f5f5f5", borderRadius: 8 };
return <div style={box}>Hello</div>;
}

Notes:

  • CSS background-color → backgroundColor
  • Some properties are unitless (e.g., lineHeight, flex).

51. What is ReactDOM, and how is it used?

Answer:
ReactDOM is the package that connects React (which builds UI elements) to the real DOM in the browser. It provides methods to render React components into HTML elements.

Example:

import ReactDOM from "react-dom/client";
import App from "./App";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

Here, ReactDOM takes the <App /> component and mounts it inside the DOM element with id “root”.

52. How do you render a React component to the DOM?

Answer:
You render a React component by selecting a DOM node (like a <div> with an id=”root”) and telling ReactDOM to place your component inside it.

Example (modern way):

import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(document.getElementById("root")).render(<App />);

53. What is the difference between ReactDOM.render and ReactDOM.createRoot?

Answer:

  • ReactDOM.render
    • Used in React 17 and earlier.
    • Syntax:
    • ReactDOM.render(<App />, document.getElementById(“root”));
    • Not compatible with React 18’s new features like concurrent rendering.
  • ReactDOM.createRoot
    • Introduced in React 18.
    • Enables modern features like concurrent rendering, automatic batching, and Suspense improvements.
    • Syntax:
    • ReactDOM.createRoot(document.getElementById(“root”)).render(<App />);

54. What is Create React App (CRA), and why is it useful?

Answer:
Create React App is a tool to quickly set up a React project without manually configuring Webpack, Babel, or other build tools. It gives you a ready-to-use environment with features like:

  • Development server with hot reloading
  • ES6+ and JSX support out of the box
  • Optimized production build
  • Built-in linting and testing setup

Example (setup command):

npx create-react-app my-app
cd my-app
npm start

55. What is the difference between development and production builds of React?

Answer:

  • Development Build
    • Includes warnings, error messages, and extra checks to help developers.
    • Not optimized for speed or size.
    • Larger bundle.
  • Production Build
    • Stripped of warnings and extra checks.
    • Minified and optimized for performance.
    • Much smaller in size and faster.

Example:
When you run npm run build in CRA, you get a production build ready to deploy.

56. How do you comment inside JSX?

Answer:
In JSX, you write comments inside {} using the JavaScript multi-line comment syntax.

Example:

return (
<div>
   {/* This is a comment */}
   <h1>Hello React</h1>
</div>
);

57. What are default exports and named exports in React components?

Answer:

  • Default export → A file exports a single main component. Import without {}.
  • Named export → A file exports multiple components or values. Import with {}.

Example:

// Default export
export default function App() { return <h1>Main App</h1>; }
// Named export
export function Header() { return <h2>Header</h2>; }

Usage:

import App from "./App";        // default
import { Header } from "./App"; // named

58. How do you reuse components in React?

Answer:
You reuse components by writing them once and using them multiple times with different props. Props make components dynamic and reusable.

Example:

function Button({ label }) {
return <button>{label}</button>;
}
// Reusing
<Button label="Login" />
<Button label="Register" />
<Button label="Submit" />

Here, the same Button component is reused with different labels.

59. What is the difference between functional components and pure components?

Answer:

  • Functional Components
    • Regular functions that return JSX.
    • Re-render every time their parent renders, even if props don’t change.
  • Pure Components (class-based or via React.memo)
    • Automatically prevent re-render if props and state are the same.
    • Used to improve performance.

Example with React.memo:

const Greeting = React.memo(function Greeting({ name }) {
return <h1>Hello {name}</h1>;
});

Here, Greeting won’t re-render unless name changes.

60. How do you handle multiple return values from a React component?

Answer:
A React component must return one root element, but inside it you can include multiple elements. Common approaches are:

  1. Wrap in a parent <div>
  2. Use Fragments (<> … </>)

Example (Fragment):

function Info() {
return (
   <>
     <h1>Title</h1>
     <p>Description goes here.</p>
   </>
);
}
Note: The interview questions and answers provided on this page have been thoughtfully compiled by our academic team. However, as the content is manually created, there may be occasional errors or omissions. If you have any questions or identify any inaccuracies, please contact us at team@learn2earnlabs.com. We appreciate your feedback and strive for continuous improvement.