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:

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?

Correct Answer:

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?

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

Correct Answer:

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

JSX

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

Advantages:

Uncontrolled Components

JSX

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

Advantages:

Why other options are incorrect?

3. How React handles error boundaries?

Correct Answer:

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?

4. What is use of setState method in React?

Correct Answer:

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?

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

Correct Answer:

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?

6. What is significance of useEffect hook in React?

Correct Answer:

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?

7. How to optimize performance in a React application?

Correct Answer:

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?

Correct Answer:

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?

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

Correct Answer:

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?

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

Correct Answer:

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?

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

Correct Answer:

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?

12. What is purpose of props object in React?

Correct Answer:

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?

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

Correct Answer:

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?

14. What is JSX in React JS?

Correct Answer:

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?

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

Correct Answer:

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.

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?

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

Correct Answer:

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.

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,

Why other options are incorrect?

17. What is role of useMemo hook in React?

Correct Answer:

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?

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

Correct Answer:

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

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

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?

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

Correct Answer:

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:

Core concept of Redux

Why use Redux?

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?

20. What is the significance of React Virtual DOM?

Correct Answer:

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?

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

Correct Answer:

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?

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

Correct Answer:

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?

Controlled component is form element whose value is:

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?

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

Correct Answer:

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:

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?

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

Correct Answer:

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 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:

Why other options are incorrect?

25. What is significance of useEffect hook in React?

Correct Answer:

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:

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?

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.