React  

React JS Intermediate Interview Questions

Background

React JS is a widely used tool which allows to build reach UI components using front end JavaScript library. React JS is also known as React.js or React.

Key purpose of this article is to:

  • Check your React JS intermediate level knowledge.

  • Uunderstand intermediate level React features along with their use-cases and examples.

  • Crack intermediate level certifications, challenges, or interviews of React JS.

In this article, each questions having four options and after each question correct answer is given along with detailed explanation and with code examples. It gives actual idea about the concept, feature or purpose of it.

Questions

  1. How to apply conditionally CSS styles in a React component?

  2. What is main difference between controlled and uncontrolled components in React forms?

  3. How React handles error boundaries?

  4. What is use of setState method in React?

  5. What is use of shouldComponentUpdate lifecycle method in React?

  6. What is significance of useEffect hook in React?

  7. How to optimize performance in a React application?

  8. What is the purpose of React Fragments?

  9. Which method is used to update state of React component?

  10. How can you prevent default behavior of an event in React?

  11. What is significance of React Router in React application?

  12. What is purpose of props object in React?

  13. What is purpose of key attribute when rendering a list of elements in React?

  14. What is JSX in React JS?

  15. What is purpose of propTypes property in React components?

  16. What is use of key prop while rendering a list of components in React?

  17. What is role of useMemo hook in React?

  18. What is key difference between React.Component and functional components in React?

  19. What is the purpose of Redux in React application?

  20. What is the significance of React Virtual DOM?

  21. How to pass parameters to event handler function in React?

  22. How does React handle forms? What are controlled components?

  23. What is use of React key prop when rendering a list of elements?

  24. What is the purpose of context API in React?

  25. What is significance of useEffect hook in React?

Answers

1. How to apply conditionally CSS styles in a React component?

  • A. Using inline styles directly in JSX code

  • B. React does not support conditional styling

  • C. Defining styles in external CSS files only

  • D. Embedding JavaScript conditions within component's HTML tags

Correct Answer:

  • D. Embedding JavaScript conditions within component's HTML tags

Explanation:

React uses JSX which allows to embed JavaScript expressions directly inside markup. Hence, it’s easy to conditionally apply CSS styles through logic such as logical &&, ternary operator, conditional variables, etc.

JSX

const isActive = true;
<div style={{ color: isActive ? 'green' : 'red' }}>  
     Status
</div>
<div className={isActive ? 'active' : 'inactive'}>  
     Status
</div>

Here, conditional inline styles applied and used conditional class name. Both approach will work because JavaScript conditions can embedded directly within JSX.

Why other options are incorrect?

  • Using inline styles directly in JSX code - It is partially correct. It complete when combined with JavaScript conditions.

  • React does not support conditional styling - It is incorrect. Because, React fully supports conditional styling.

  • Defining styles in external CSS files only - It is not correct. Only external CSS can’t handle logic without JS.

2. What is main difference between controlled and uncontrolled components in React forms?

  • A. Controlled components rely on state, while uncontrolled components don't

  • B. Uncontrolled components are faster than controlled components

  • C. Controlled components are not used for form handling

  • D. Controlled components are deprecated in React

Correct Answer:

  • A. Controlled components rely on state, while uncontrolled components don't

Explanation:

Main difference between controlled and uncontrolled components in React forms is how their state and form data are managed. Controlled components have their value driven by React state, while uncontrolled components let the browser's Document Object Model (DOM) maintain the source of truth.

Controlled Components

  • Form data is controlled by React state.

  • Input values are stored in component state using useState or this.state.

  • Every change is handled through onChange event.

  • React is single source of truth.

JSX

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

Advantages:

  • Easier validation.

  • Better control over form behavior.

  • Predictable state management.

Uncontrolled Components

  • Form data is managed by DOM itself.

  • Uses ref to access input values instead of state.

  • React does not track value changes in real time.

JSX

function Form() {
  const inputRef = React.useRef();
  return <input ref={inputRef} />;
}

Advantages:

  • Less code.

  • Useful for quick or simple forms.

Why other options are incorrect?

  • Uncontrolled components are faster than controlled components - This is not true because performance difference is usually negligible and it depends on use case.

  • Controlled components are not used for form handling - It is incorrect because controlled components are the preferred method.

  • Controlled components are deprecated in React - Incorrect because controlled components are recommended and widely used in React.

3. How React handles error boundaries?

  • A. React automatically catches and handles all errors

  • B. Error boundaries are not supported in React

  • C. Using try...catch statement in every component

  • D. Using componentDidCatch lifecycle method in error boundary components

Correct Answer:

  • D. Using componentDidCatch lifecycle method in error boundary components

Explanation:

In React, error boundaries are special components used to catch JavaScript errors. Error might occur in their child component tree during rendering, lifecycle methods or child components constructors.

In class components componentDidCatch and getDerivedStateFromError lifecycle methods are used to handle error boundaries.

JSX

class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError(error) {
    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;
  }
}

Here, componentDidCatch(error, info) is used to log error information. Static getDerivedStateFromError(error) is used to update state and render fallback UI.

Why other options are incorrect?

  • React automatically catches and handles all errors - It is incorrect. Explicitly define error boundaries .

  • Error boundaries are not supported in React - It is incorrect. Error boundaries is core React feature.

  • By using the try...catch statement in every component - In JSX, try...catch does not work for rendering or lifecycle errors.

4. What is use of setState method in React?

  • A. It updates HTML content of a component

  • B. It changes state of a component and triggers re-render

  • C. It defines styling for a component

  • D. It handles user input events

Correct Answer:

  • B. It changes state of a component and triggers re-render

Explanation:

setState method is used to update state of component. Component is re-rendered automatically when state is changed using setState.

JSX

JSXthis.setState({ count: this.state.count + 1 });

Here, setState updates component’s state and re-runs render() to update DOM efficiently using Virtual DOM.

Why other options are incorrect?

  • It updates HTML content of a component - UI updated through state change instead of direct HTML manipulation.

  • It defines styling for a component - Styling is handled through CSS, inline styles, or libraries instead of setState.

  • It handles user input events - It is incorrect because onClick, onChange, etc. event handlers handles inputs. setState may called through such event handlers.

5. What is use of shouldComponentUpdate lifecycle method in React?

  • A. Used for fetching data from an external API

  • B. Used for cleaning up resources before a component is removed from the DOM

  • C. Used to handle component initialization logic

  • D. Used to decide whether a component should re-render or not

Correct Answer:

  • D. Used to decide whether a component should re-render or not

Explanation:

The purpose of shouldComponentUpdate lifecycle method in React is to optimize performance by controlling component re-rendering while it’s props or state change. It is called before rendering.

It is called before the rendering. When new props or state is received it returns true or false. React proceeds with re-rendering if it is true and for false case re-rendering not happen.

JSX

shouldComponentUpdate(nextProps, nextState) {
  return nextProps.value !== this.props.value;
}

Here, it is preventing unnecessary rendering. Hence, it improves application efficiency. It plays important role especially for large and complex components.

Why other options are incorrect?

  • Used for fetching data from an external API - componentDidMount or useEffect hook are used for fetching data from an external API.

  • Used for cleaning up resources before a component is removed from the DOM - componentWillUnmount is used for cleaning up resources.

  • Used to handle component initialization logic - componentDidMount or constructor are used to handles component initialization logic.

6. What is significance of useEffect hook in React?

  • A. Managing component state

  • B. Handling user inputs

  • C. Performing side effects in functional components

  • D. Creating custom hooks

Correct Answer:

  • C. Performing side effects in functional components

Explanation:

In React, useEffect hook is used in functional components and it handles side effects operations which affect something outside component rendering logic.

Some common side effects are data fetching from APIs, events subscribing and unsubscribing, manually updating DOM, setting up timer and interval, with external system synchronizing state.

Before useEffect, such tasks were manages using lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

JSX

useEffect(() => {
  fetchData();
  return () => {
    cleanupResources();
  };
}, []);

Here, effect runs after component rendering and cleanup function runs while component unmounts or before re-running effect.

Why other options are incorrect?

  • Managing component state - useState is used to manage state.

  • Handling user inputs - onChange, onClick, etc. event handlers are used to handle user inputs.

  • Creating custom hooks - Primary purpose of useEffect hook is not to create custom hooks.

7. How to optimize performance in a React application?

  • A. Use functional components instead of class components

  • B. Implement shouldComponentUpdate lifecycle method

  • C. Memoize expensive calculations using the useMemo hook

  • D. All of the above

Correct Answer:

  • D. All of the above

Explanation:

In React application performance can be optimized through several ways such as using functional component, implement shouldComponentUpdate method, using useMemo hook, etc.

Use functional components instead of class components - Functional components are light, simple and easy to optimize. useMemo, useCallback, useEffect, etc. hooks improves performance effectively. Optimization and modern features are designed around functional components instead of class.

Implement shouldComponentUpdate lifecycle method - It exists in class component. It providing control to preventing unnecessary re-rendering. It improves render performance in complex scenarios.

JSX

shouldComponentUpdate(nextProps, nextState) {
  return nextProps.value !== this.props.value;
}

Memoize expensive calculations using the useMemo hook - It prevents recalculation of expensive computation on every render. It recalculates only when dependencies are change. It is useful especially for complex calculations and large data sets.

JSX

const expensiveValue = useMemo(() => computeExpensiveValue(data), [data]);

8. What is the purpose of React Fragments?

  • A. They are used for creating animated transitions in React

  • B. They represent lightweight version of React component

  • C. They allow grouping multiple elements without adding an extra node to the DOM

  • D. They are alternative to React components

Correct Answer:

  • C. They allow grouping multiple elements without adding an extra node to the DOM

Explanation:

React Fragment is used to group multiple child elements without adding extra elements such as <div> into DOM. It makes DOM clean and avoids unnecessary markup. It is used return multiple child elements. It is used to avoid extra DOM elements.

JSX - Using Fragment short form

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

JSX - Equivalent long form

<React.Fragment>
  <h1>Title</h1>
  <p>Description</p>
</React.Fragment>

Here, both versions render same output without adding extra wrapper elements in DOM.

Why other options are incorrect?

  • They are used for creating animated transitions in React - react-transition-group, framer-motion, etc. libraries are used to handled animations.

  • They represent lightweight version of React component - Fragment is not a component. It is a grouping mechanism.

  • They are alternative to React components - Fragment doesn’t replace component.

9. Which method is used to update state of React component?

  • A. this.setState()

  • B. this.updateState()

  • C. this.modifyState()

  • D. this.changeState()

Correct Answer:

  • A. this.setState()

Explanation:

setState() method is used to update the state of a React component. React re-renders, when state of component is changed and UI reflects only updates using virtual DOM.

JSX

this.setState({ count: this.state.count + 1 });

Here, never modify state directly e.g. this.state.count = 1. Because setState() ensures that updates will be handle efficiently and correctly through React.

Why other options are incorrect?

  • this.updateState() - Not a React method.

  • this.modifyState() - Not such method exists.

  • this.changeState() - Invalid method.

10. How can you prevent default behavior of an event in React?

  • A. By using e.preventDefault() method within event handler

  • B. React automatically prevents default behavior, no additional steps are needed

  • C. By setting event.preventDefault property to false

  • D. It is not possible to prevent the default behavior in React

Correct Answer:

  • A. By using e.preventDefault() method within event handler

Explanation:

e.preventDefault() method is used to prevent default behavior of event. In React, Events are handled using Synthetic Events. Form submission reloads page, link navigates, etc. are default behaviour of events. To prevent such default event behavior call preventDefault() on event object.

JSX

function handleSubmit(e) {
  e.preventDefault(); // Prevents page reload
  console.log("Form submitted!");
}
<form onSubmit={handleSubmit}>
  <button type="submit">Submit</button>
</form>

This approach is commonly used to handle form submission, anchor <a> click, button click with default browser actions, etc.

Why other options are incorrect?

  • React automatically prevents default behavior, no additional steps are needed - React does not prevent default behavior, additional steps are required.

  • By setting event.preventDefault property to false - event.preventDefault is not boolean property but preventDefault() is method.

  • It is not possible to prevent the default behavior in React - It is incorrect. It is possible.

11. What is significance of React Router in React application?

  • A. Managing state in React components

  • B. Handling HTTP requests

  • C. Navigation and routing in a single-page application

  • D. Styling React components

Correct Answer:

  • C. Navigation and routing in a single-page application

Explanation:

The purpose of React Router in a React application is to handle client-side navigation and routing. It allows to create Single-page application (SPA). In SPA, different views are rendered based on URL without page reloading.

React Router is used to define routes which maps URLs to components. It allows to navigation between pages using links such as <Link>, <NavLink>, etc. It permits to access route parameters and query strings. It implements nested routes and protected routes.

JSX

import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
  return (
    <BrowserRouter>
                     <Routes>
                               <Route path="/" element={<Home />} />
                               <Route path="/about" element={<About />} />
                     </Routes>
              </BrowserRouter>
  );
}

Here, it allows effective navigation within application and keeps it faster and user-friendly.

Why other options are incorrect?

  • Managing state in React components - tools such as useState, useReducer, or libraries like Redux are used to manage state.

  • Handling HTTP requests - axios, fetch, etc. networking libraries are used to handle HTTP requests.

  • Styling React components - inline styles, CSS, CSS-in-JS i.e. styled-components, etc. are used for styling components.

12. What is purpose of props object in React?

  • A. To store component state

  • B. To handle component events

  • C. To pass data from parent to child components

  • D. To define component methods

Correct Answer:

  • C. To pass data from parent to child components

Explanation:

Props is short form of properties. It is used to pass data and configuration from parent to child component. Using it components became reusable, dynamic, and configurable. It is read only i.e. immutable. It is passed as attributes to components.

JSX - Parent and Child components

function Parent() {
  return <Child name="Bharat" age={25} />;
}
function Child(props) {
  return <h1>Hello, {props.name}! You are {props.age} years old.</h1>;
}

Here, name and age are passed from parent to child component using props.

Why other options are incorrect?

  • To store component state - useState, this.state, etc. are used to manage state.

  • To handle component events - Event handlers are used to handle events.

  • To define component methods - Methods are defined inside components.

13. What is purpose of key attribute when rendering a list of elements in React?

  • A. It sets the font size for each element

  • B. It provides a unique identifier for each element in the list

  • C. It determines the color of each element

  • D. It controls the visibility of each element

Correct Answer:

  • B. It provides a unique identifier for each element in the list

Explanation:

Key attribute is used to render list of elements with map() and it gives unique identity to each element. It helps re-rendering efficiency via only changed elements.

It improves performance by avoiding unnecessary re-rendering through identifying which items to re-render based on changes.

JSX

const items = ["Apple", "Banana", "Cherry"];
<ul>
       {items.map((item, index) => (
         <li key={index}>{item}</li>
       ))}
</ul>

Here, each <li> has one key so React can track it properly. It is recommended to use unique ID instead of index.

Why other options are incorrect?

  • It sets the font size for each element - Font size is controlled through CSS instead of key.

  • It determines the color of each element - It is incorrect as colors are defined by styles or classes.

  • It controls the visibility of each element - Visibility is handled using conditional rendering or CSS instead of key.

14. What is JSX in React JS?

  • A. JavaScript Syntax Extension

  • B. XML-like Script for JavaScript

  • C. JSX is not used in React

  • D. Java Syntax Extension

Correct Answer:

  • A. JavaScript Syntax Extension

Explanation:

JSX is short form of JavaScript Syntax Extension. In React JS it is a syntax extension for JavaScript. It is used to write HTML like code inside JavaScript and it makes UI code more readable and expressive. JSX is not HTML but it looks like HTML.

JSX

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

Equivalent JavaScript

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

JSX makes React components easier to understand by keeping structure and logic together.

Why other options are incorrect?

  • XML-like Script for JavaScript - It is incorrect as JSX looks only similar to XML.

  • JSX is not used in React - Incorrect because JSX is commonly used in React applications.

  • Java Syntax Extension - It is incorrect because JSX has no relation with Java.

15. What is purpose of propTypes property in React components?

  • A. To define visual appearance of a component

  • B. To specify types of data expected by a component's props

  • C. To determine the position of a component on the screen

  • D. To validate state of a component

Correct Answer:

  • B. To specify the types of data expected by a component's props

Explanation:

In React components, propTypes are used for type check the props passed to the components. It make sure that a component receives a correct data type. It improves reliability and makes debugging easier.

  • It only runs in development mode only not in production.

  • It helps to catch bugs caused through incorrect prop usage.

  • It improved code maintainability and readability.

  • prop-types package is used to implement it.

JSX

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

Here, in case if incorrect prop types are passed, in console it logs a warning.

Why other options are incorrect?

  • To define visual appearance of a component - Incorrect because appearance is managed using CSS, styles, or styled components.

  • To determine position of a component on the screen - It is incorrect because layout is handled via CSS or layout systems.

  • To validate state of a component - propTypes validates only props instead of state of a component.

16. What is use of key prop while rendering a list of components in React?

  • A. It defines styling for each component in the list

  • B. It sets state for each component

  • C. The key prop is not required in React component lists

  • D. It ensures a unique identifier for each component, aiding in efficient updates

Correct Answer:

  • D. It ensures a unique identifier for each component, aiding in efficient updates

Explanation:

In React, key prop is used during rendering a list of component using map(). It provides unique identity to each element and React uses it during its reconciliation process.

Without proper keys, React may re-render more elements instead of only necessary which potentially causing performance issues or UI related bugs.

  • It helps to identify which items have changed.

  • Determines which items were added or removed.

  • Using it React updates only affected components instead of more elements which improves performance.

JSX

const users = [
  { id: 1, name: "Amit" },
  { id: 2, name: "Navin" },
  { id: 3, name: "Ravi" }
];
<ul>
  {users.map(user => (
    <li key={user.id}>{user.name}</li>
  ))}
</ul>

Note,

  • user.id is used as key for unique identity and it gives each list item a unique and consistent identifier.

  • Recommend practice is to use table’s unique column value instead of array index as keys.

  • Array index can be used only when list is static and never change.

Why other options are incorrect?

  • It defines styling for each component in the list - Instead of keys, CSS or inline styles are used for styling.

  • It sets state for each component - It is incorrect because state is managed using useState or this.state.

  • The key prop is not required in React component lists - Right, app may work without keys but may cause performance issue or UI related bugs. React, strongly recommends to use them and issues warnings when they are missing.

17. What is role of useMemo hook in React?

  • A. To perform asynchronous operations in functional components

  • B. To memoize the result of a computationally expensive function

  • C. To manage local component state

  • D. To create custom hooks

Correct Answer:

  • B. To memoize the result of a computationally expensive function

Explanation:

In React, useMemo hook is used to optimize performance by caching (memoizing) result of calculation. Hence, it does not need to be recalculated on every render.

Recalculation only perform with useMemo when one of its dependencies changes. It is useful especially when there is expensive calculation and which is not required to run on every render.

JSX

import { useMemo } from "react";
function ProductList({ products }) {
  const expensiveCalculation = useMemo(() => {
    return products.filter(product => product.price > 1000);
  }, [products]);
  return (
    <ul>
                     {expensiveCalculation.map(product => (
                          <li key={product.id}>{product.name}</li>
                     ))}
    </ul>
  );
}

Here, filtered list is only recalculated when products changes and it improves performance.

Why other options are incorrect?

  • To perform asynchronous operations in functional components - useEffect is used for asynchronous operations.

  • To manage local component state - useState is used for local state management.

  • To create custom hooks - Custom hooks are regular JavaScript functions which may use hooks like useMemo, but that is not its actual purpose.

18. What is key difference between React.Component and functional components in React?

  • A. React.Component is used for class components, while functional components are for stateless ones

  • B. There is no difference; they can be used interchangeably

  • C. Functional components are deprecated in React

  • D. React.Component is not a valid class in React

Correct Answer:

  • A. React.Component is used for class components, while functional components are for stateless ones

Explanation:

In React, components mainly created in two ways: class components and functional components. Main difference is in syntax, state handling, and lifecycle management.

Class Components

  • It is created using ES6 (ECMAScript 2015) classes.

  • It must extend React.Component.

  • It uses this.state and this.setState().

  • It is traditionally used when components needed:

  • Internal state

  • Lifecycle methods (e.g. componentDidMount, shouldComponentUpdate)

JSX

class Counter extends React.Component {
  state = { count: 0 };
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    return <button onClick={this.increment}>{this.state.count}</button>;
  }
}

Functional Components

  • It is defined as plain JavaScript functions.

  • It originally considered stateless.

  • It is simpler and easier to read.

  • Due to introduction of React Hooks (React 16.8+), functional components can now:

  • It can manage state using useState.

  • It can handle side effects via useEffect.

  • It replace mostly all class component use cases.

JSX

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

Functional components are the absolute standard and officially recommended approach in modern React development.

Since introduction of Hooks, React team has actively discouraged using class components for new code, though classes remain supported for legacy systems.

Why other options are incorrect?

  • There is no difference; they can be used interchangeably - This is incorrect. They differ in syntax, features, and historical usage.

  • Functional components are deprecated in React - Incorrect, because functional components are recommended and preferred in modern React.

  • React.Component is not a valid class in React - False, because of it is a core React API.

19. What is the purpose of Redux in React application?

  • A. Redux is styling library for React components

  • B. It is state management library for managing global state in complex applications

  • C. Redux is alternative to the React router for navigation

  • D. It is used for creating animations in React applications

Correct Answer:

  • B. It is state management library for managing global state in complex applications

Explanation:

Redux is a predictable state management library. In React, it is used to manage application wide global states. Generally it is used in large or complex application where many components requires to share and update same data.

Redux helps to solve problems:

  • Prop drilling i.e. passing props through many layers.

  • State becomes difficult to manage as application grows.

  • Unpredictable state changes.

Core concept of Redux

  • Store: Holds global application state.

  • Actions: Plain objects which describes what happened.

  • Reducers: Pure functions which describe how state changes.

  • Single source of truth: All states lives in one store.

Why use Redux?

  • Predictable and centralized state management.

  • Easy debugging.

  • Better scalability for large applications.

  • Clear logic separation.

JavaScript - Conceptual example

// Action
{ type: "INCREMENT" }
// Reducer
function counter(state = 0, action) {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    default:
      return state;
  }
}

Why other options are incorrect?

  • Redux is styling library for React components - It is incorrect because of styling is handled by CSS, styled-components, etc.

  • Redux is alternative to the React router for navigation - It is not correct because routing or navigation is handled by React Router.

  • It is used for creating animations in React applications - Framer Motion or React Spring libraries are used for animation instead of Redux.

20. What is the significance of React Virtual DOM?

  • A. JavaScript library for creating virtual reality applications

  • B. Lightweight version of the Document Object Model

  • C. virtual representation of the actual DOM in memory for efficient updates

  • D. Tool for managing database connections in React applications

Correct Answer:

  • C. Virtual representation of the actual DOM in memory for efficient updates

Explanation:

React Virtual DOM is in-memory and lightweight copy of real browser DOM. It is used to optimize performance while updating user interface.

React creates new Virtual DOM tree when component’s state or props changed. In React, diffing process compares new tree wit previous tree. React calculates minimal changes required. Finally, only needed changes are applied to actual DOM.

This approach avoids direct DOM manipulations which is expensive and makes React app fast and efficient.

Why other options are incorrect?

  • JavaScript library for creating virtual reality applications - It describes VR frameworks instead of Virtual DOM.

  • Lightweight version of the Document Object Model - It is incomplete and doesn’t explain purpose.

  • Tool for managing database connections in React applications - It is incorrect because React doesn’t handle databases directly.

21. How to pass parameters to event handler function in React?

  • A. By directly embedding parameters in event handler

  • B. React does not support passing parameters to event handlers

  • C. Parameters are automatically passed to event handlers in React

  • D. By using the bind method on event handler

Correct Answer:

  • D. By using the bind method on event handler

Explanation:

In React, one can pass parameters to an event handler function by binding arguments to handler function. This approach is commonly used in class components.

JSX- using bind

class Button extends React.Component {
  handleClick(id) {
    console.log(id);
  }
  render() {
    return (
      <button onClick={this.handleClick.bind(this, 1)}>
        Click Me
      </button>
    );
  }
}

Here, bind(this, 1) passes parameter 1 to handleClick. Function is not executed immediately, only when event occurs.

React developers commonly use arrow functions, which correspond to this option. It is alternate modern approach. This approach is common especially in functional components.

JSX

<button onClick={() => this.handleClick(1)}>
  Click Me
</button>

Why other options are incorrect?

  • By directly embedding parameters in event handler - This is incorrect because it would immediately invoke function instead of waiting for event.

  • React does not support passing parameters to event handlers - React fully supports passing parameters to event handlers.

  • Parameters are automatically passed to event handlers in React - It is not correct because only event object is passed automatically while custom parameters can not.

22. How does React handle forms? What are controlled components?

  • A. React forms automatically handle state changes without any special considerations

  • B. Controlled components are React components with a predefined style

  • C. React uses the useState hook to manage form state, and controlled components are tied to the component's state

  • D. Forms are not supported in React applications

Correct Answer:

  • C. React uses the useState hook to manage form state, and controlled components are tied to the component's state

Explanation:

React handles forms using component state instead of letting browser manage input values directly. It leads concept of controlled components.

How React Handles Forms?

  • Form elements such as <input>, <textarea>, and <select> do not manage their own state.

  • React controls form data via state.

  • User input updates state through event handlers e.g., onChange.

  • State then determines what is displayed in form element.

  • It creates a single source of truth for form data.

Controlled component is form element whose value is:

  • Stored in React state.

  • Updated using event handlers.

  • Fully controlled by React component.

JSX

import { useState } from "react";
function LoginForm() {
  const [username, setUsername] = useState("");
  return (
    <form>
                <input type="text" value={username}  onChange={(e) => setUsername(e.target.value)}  />
             </form>
  );
}

Here, input’s value comes from React state, every keystroke updates state, React controls both data and UI.

Why other options are incorrect?

  • React forms automatically handle state changes without any special considerations - It is incorrect because for state handling explicitly coded to be written.

  • Controlled components are React components with a predefined style - Styling is not related to controlled components.

  • Forms are not supported in React applications - It is not correct because forms are fully supported and commonly used in React app.

23. What is use of React key prop when rendering a list of elements?

  • A. It defines the styling for each element in the list

  • B. It ensures a unique identifier for each element, aiding in efficient updates

  • C. The key prop is not required when rendering lists in React

  • D. It controls the visibility of each element

Correct Answer:

  • B. It ensures a unique identifier for each element, aiding in efficient updates

Explanation:

In React, while rendering list of elements commonly using map() key prop gives each element unique identity. React uses that key during its reconciliation (diffing) process to determine what has changed between renders.

Key benefits of key prop:

  • It efficiently updates only elements those are changed.

  • It correctly handles insertions, deletions, and reordering.

  • It avoids unnecessary re-renders and potential UI bugs.

JSX

const items = [
  { id: 1, name: "Apple" },
  { id: 2, name: "Banana" },
  { id: 3, name: "Cherry" }
];
<ul>
  {items.map(item => (
    <li key={item.id}>{item.name}</li>
  ))}
</ul>

Here, item.id is used as key which ensues each list item is uniquely identified across renders. Best practice is to use a stable unique ID as the key instead of using array indexes unless the list is static or never reordered.

Why other options are incorrect?

  • It defines the styling for each element in the list - Styling is handled by CSS or inline styles instead of keys.

  • The key prop is not required when rendering lists in React - Partially true, because React may still render list but it will show warnings and performance may suffer.

  • It controls the visibility of each element - It is incorrect because visibility is handled through conditional rendering or CSS instead of keys.

24. What is the purpose of context API in React?

  • A. It provides a way to pass data through the component tree without manually passing props

  • B. It is used for handling HTTP requests in React applications

  • C. It controls the visual layout of components

  • D. context is not a valid API in React

Correct Answer:

  • A. It provides a way to pass data through the component tree without manually passing props

Explanation:

In React, context API is designed to solve problem of prop drilling which occurs when data needs to be passed through many levels of components that don’t actually need data themselves.

When context used?

  • To create global-like data such as theme, user authentication, language, settings, etc.

  • To allow to access data directly to any component in tree.

  • To avoid passing props manually at each and every level.

  • To make code clean, more maintainable and scalable.

To use context API - create context, provide data, and consume data.

JSX - Create Context

const ThemeContext = React.createContext();

JSX - Provide Data

<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>

JSX - Consume Data

const theme = useContext(ThemeContext);

Common use cases:

  • Authentication data such as user info, tokens, etc.

  • Theme such as dark/light mode.

  • Localization such as language settings.

  • Global configuration values.

Why other options are incorrect?

  • It is used for handling HTTP requests in React applications - HTTP requests are handled using fetch, axios, or similar libraries instead of context API.

  • It controls the visual layout of components - It is incorrect because layout is controlled by CSS and UI frameworks.

  • context is not a valid API in React - Context is a core and widely used React API.

25. What is significance of useEffect hook in React?

  • A. To create custom hooks in functional components

  • B. To manage component state in class components

  • C. To perform side effects in functional components

  • D. useEffect is not a valid hook in React

Correct Answer:

  • C. To perform side effects in functional components

Explanation:

In React, useEffect hook is used in functional components to handle side effects such as operations which occurs outside normal rendering process of component.

Before useEffect hooks, side effects were handled in class components using lifecycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount.

useEffect replaces all these in single and unified API.

Common use cases:

  • Fetching data from API.

  • Setting up subscription or event listener.

  • Updating document title.

  • Managing timers such as setTimeout, setInterval.

  • Cleaning up resources when component unmounts.

JSX

import { useEffect } from "react";
function Example() {
  useEffect(() => {
    console.log("Component mounted");
    return () => {
      console.log("Component unmounted");
    };
  }, []);
  return <div>Hello World</div>;
}

Here, effect runs after render. Cleanup function runs on unmount or before effect re-runs. Dependency array ([]) controls when effect runs.

Why other options are incorrect?

  • To create custom hooks in functional components - It is incorrect because custom hooks may use useEffect, but that is not its purpose.

  • To manage component state in class components - Not correct because state is managed with useState (functional) or this.state (class).

  • useEffect is not a valid hook in React - useEffect is core and widely used React hook.

Summary

Here, complete explanation is given for every topics. Hence, you will be able to crack intermediate level certifications, challenges, or interviews of React JS.