React Js Interview Questions and Answers


React js interview questions and answers has you covered. Whether you’re a seasoned developer or just starting your journey with React, these curated questions and expert responses will help you ace your interview. Dive into the world of React.js and ensure you’re well-equipped to impress potential employers with your knowledge and skills.

Why React Js Interview Questions and Answers ?

React.js is a flexible, efficient, and open-source JavaScript framework library to help developers to create simple, scalable, and fast web applications. A former Facebook employee also created this framework called Jordan Walke.

Developers with experience in the JavaScript background can easily make web applications by using React. React Hooks also allows people to use the state and other efficient features of the platform, which requires a class written by professionals. In other words, React Hooks are the features and functions that connect the state with the lifecycle features of the Component’s function. 

Know More About React.js

The selection of appropriate technology for web or app development is becoming more intricate and also challenging. JavaScript’s tools are firming their roots steadily in the marketplace, and also the demand for React professionals are roaring. React is ideal for front-end developers because of the quick learning curve, reusable components, and clean abstraction. We have provided React.js interview questions and answers to increase your chances of answering most of the questions asked by the employer during the interview.

Features Of React.js

Before we move on with the react.js interview questions and Answers, let us look at the features and benefits of react.js.

  • The platform features a document object model, a critical part of the web, as it also classifies into modules and helps with code execution. Usually, the JavaScript Framework updates the DOM at once, potentially slowing down the application. But with the help of the virtual DOM reacting, it will make the exact copy of the real DOM.
  • React.js is mainly about the Component. However, the applications made with React.js have multiple components, and each has its control and logic. Developers can use them to maintain the code when working on a large project.
  • Since the platform uses the JSX file, the application is easy to code and understand. Developers can also easily use it and learn it. 

1 . What is React?

React is a front-end and open-source JavaScript library that is generally useful in developing user interfaces for applications with a single page. It also helps build complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.

The important features of React are:

  • It supports server-side rendering.
  • It will use the virtual DOM rather than the real DOM (Data Object Model), as RealDOM manipulations are expensive.
  • Also, it follows unidirectional data binding or data flow.
  • It uses reusable and also composable UI components for developing the view.

2 . What are the advantages of ReactJS?

Below are the advantages of ReactJS:

  1. Increases the application’s performance with Virtual DOM
  2.  JSX makes code also is easy to read and write
  3.  It renders both on the client and server side.
  4.  Easy to integrate with other frameworks (Angular, BackboneJS) since it is only a view library
  5.  Easy to write UI Test cases and integration with tools such as JEST.
  • Use Virtual DOM to improve efficiency: React uses virtual DOM to render the view. As the name suggests, virtual DOM is a virtual representation of the real DOM. A new virtual DOM also gets created each time the data changes in a react app. Creating a virtual DOM is much faster than rendering the UI inside the browser. Therefore, with the use of virtual DOM, the app’s efficiency improves.
  •  Gentle learning curve: React has a gentle learning curve compared to frameworks like Angular. Generally, anyone with little knowledge of javascript can start building web applications using React.
  •  SEO friendly: React allows developers to develop engaging user interfaces that also navigates in various search engines. It also allows server-side rendering, which boosts the SEO of an app.
  •  Reusable components: React uses component-based architecture for developing applications. Components are generally independent and reusable bits of code. 
  •  Huge ecosystem of libraries to choose from: React allows you to choose the tools, libraries, and also architecture for developing an application based on your requirement.

3 . How does React work?

React is a JavaScript library for building user interfaces. It works by creating a virtual representation of the user interface, known as the Virtual DOM. When data changes, React compares the new Virtual DOM with the previous one and calculates the most efficient way to update the actual DOM, minimizing unnecessary re-rendering. This process, called “reconciliation,” makes React highly efficient and ensures a smooth user experience. React uses a component-based architecture, where the UI is broken down into reusable components, making it easy to develop and maintain complex applications. It also supports one-way data flow, making it predictable and easier to debug.

4 . What is the use of refs?

In React, refs provide a way to access and interact with the real DOM elements directly. They are typically used for tasks that require imperative behavior, like managing focus, triggering animations, or integrating with non-React libraries.

There are a few good use cases for refs:

For example,

  • Managing focus, text selection, or also media playback.
  •  Triggering imperative animations.
  •  Integrating with third-party DOM libraries.

Let’s say you have a form component and want to focus on an input field when the component mounts. You can use refs to achieve this:

import React, { Component } from 'react';

class MyForm extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <div>
        <input ref={this.inputRef} type="text" />
        <button>Submit</button>
      </div>
    );
  }
}

export default MyForm;

In this example, we create a ref (inputRef) and attach it to the input field. When the component mounts, we use the this.inputRef.current.focus() to programmatically focus on the input field, enhancing the user experience.

Refs are a powerful tool, but they should be used sparingly since they can bypass React’s declarative nature and make your code less predictable.

5 . What are the limitations of React?

React, like any technology, has its strengths and limitations. Here are some common limitations of React:

  • Steep Learning Curve: React has a learning curve, especially for beginners who are new to concepts like JSX, virtual DOM, and state management. While it provides powerful features, it may take time for developers to become proficient.
  •  JSX Complexity: JSX, while powerful, can become complex, especially in larger applications. The mix of JavaScript and HTML syntax may be challenging for some developers.
  • Tooling Overhead: Setting up a React project can involve a complex tooling ecosystem, including build tools like Webpack and Babel. This can be overwhelming for newcomers or those who prefer simplicity.
  •  Flux Architecture Overhead: While React itself provides the view layer, additional libraries or patterns (like Flux or Redux) are often needed for state management in larger applications. This can introduce additional complexity and boilerplate code.
  • SEO Challenges: React applications are often single-page applications (SPAs) that dynamically update content. Search engines may have difficulty indexing these pages, potentially impacting SEO. Techniques like server-side rendering (SSR) can be used to address this, but they add complexity.
  • Performance Concerns: While React’s virtual DOM helps optimize rendering, inefficient use of state or rendering too many components can still lead to performance issues. React’s performance can be optimized, but developers need to be mindful of best practices.
  • Overhead of Abstraction: React’s abstraction of the DOM and its own component model can lead to a performance overhead, especially for simple applications. In some cases, a lighter library or vanilla JavaScript may be more appropriate.
  • Large File Size: React itself is relatively small, but when combined with other libraries and tools, the overall file size of a React application can become substantial. This may impact the application’s load time, especially on slower network connections.
  • Lack of Official Guidelines: React is a library for building user interfaces, not a complete framework. This can lead to a lack of official guidelines on how to structure and organize code, leaving it up to developers to make decisions.

6 . What are props in React?

Props are inputs to a React component. They are single values or objects containing values passed to React Components on creation using a naming convention similar to HTML tag attributes. i.e., They are data passed down from a parent component to a child component.

The primary purpose of props in React is to provide the following component functionality:

  1. Pass custom data to your React component.
  2.  Trigger state changes.
  3. Generally, use via this. Props. reactProp inside component’s render() method.

For Example:

// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const greeting = "Hello, world!";
  return (
    <div>
      <ChildComponent message={greeting} />
    </div>
  );
}

export default ParentComponent;

// ChildComponent.js
import React from 'react';

function ChildComponent(props) {
  return (
    <div>
      <p>{props.message}</p>
    </div>
  );
}

export default ChildComponent;

In this example, the ParentComponent passes the greeting message as a prop to the ChildComponent, which then displays it. Props allow data to flow from parent to child components, making it easy to customize and reuse components in your React applications.

7 . What is Context API in ReactJS?

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context shares data that is “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. Using context, we can also avoid passing props through intermediate elements.

For Example:

Imagine you’re building a multi-language app. You can use the Context API to store the selected language and provide it to all components without prop drilling. First, you create a context with createContext and wrap your app with a Provider:

const LanguageContext = React.createContext();

function App() {
  const [language, setLanguage] = useState('en');
  
  return (
    <LanguageContext.Provider value={{ language, setLanguage }}>
      <Header />
      <MainContent />
    </LanguageContext.Provider>
  );
}

Now, any component can access the selected language using useContext. This simplifies language handling across your app, ensuring a consistent user experience.

8 . What is state () in React?

The useState() is a built-in React Hook that allows you to have state variables in functional components. you can use it when the DOM has something that is dynamically manipulating/controlling.

In the below-given example code, The state (0) will return a tuple where the count is the first parameter that represents the counter’s current state, and also the second parameter set counter method will allow us to update the state of the counter.

We can use the setCounter() method to update the state of the count anywhere. For example, we use setCounter() inside the setCount function. The idea with hooks is also popular to keep our code more functional and avoid class-based components if they are not required.

import React, { Component } from 'react';

class Counter extends Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
  }

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

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default Counter;

In this example, the state object is used to keep track of the count value, which can change when the “Increment” button is clicked. React automatically updates the DOM when the state changes, ensuring a responsive user interface.

9 . What are the keys in React?

A key is a special string attribute that needs to be included when using lists of elements.

Example of a list using key –

const ids = [1,2,3,4,5];

const listElements = ids.map((id)=>{

return(

<li key={id.toString()}>

  {id}

</li>

)})

Importance of keys –

  • Keys help react and identify which elements were added, changed, or removed.
  •  Use keys should array elements to provide each Component’s unique identity.
  •  With keys, React also understands the order and uniqueness of each element.
  •  With keys, React has also an idea of which particular element was deleted, edited, and added.
  •  We use Keys generally for displaying a list of data coming from an API.

10 . What is JSX?

JSX stands for JavaScript XML. It allows us to write HTML inside JavaScript and place them in the DOM without using functions like appendChild( ) or createElement( ).

As stated in the official docs of React, JSX provides syntactic sugar for React.createElement( ) function.

const MyComponent = () => {
  return (
    <div>
      <h1>Hello, JSX!</h1>
      <p>This is a JSX example.</p>
    </div>
  );
}

In this example, the <div>, <h1>, and <p> tags within the JavaScript code are written using JSX. This approach simplifies UI development in React by blending HTML-like elements with JavaScript logic.

11. What are the differences between functional and class components?

Before the introduction of Hooks in React, functional components were called stateless components and were behind class components on a feature basis. After the opening of Hooks, functional components are equivalent to class components.

Although functional components are the new trend, the React team insists on keeping class components in React. Therefore, it is important to know how these components differ.

On the following basis, let’s compare functional and class components:

Declaration

Functional components are nothing but JavaScript functions and, therefore, you can be declare them using an arrow function or the function keyword:

function card(props){

   return(

      <div className="main-container">

        <h2>Title of the card</h2>

      </div>

    )}

   const card = (props) =>{

    return(

      <div className="main-container">

        <h2>Title of the card</h2>

      </div>

    ) }

Class components, on the other hand, are declared using the ES6 class:

Class Card extends React. Component{

  constructor(props){

     super(props);}

    render(){

      return(

        <div className="main-container">

          <h2>Title of the card</h2>

        </div>

      )}}

Props

  • Handling props

Let’s render the following Component with props and analyze how functional and class components handle props:

<Student Info name="Vivek" rollNumber="23" />

In functional components, the handling of props is pretty straightforward. Any prop provided as an argument to a functional component can be directly used inside HTML elements:

function StudentInfo(props){

   return(

     <div className="main">

       <h2>{props.name}</h2>

       <h4>{props.rollNumber}</h4>

     </div>

   )

 }

 

In the case of class components, you can handle props are differently:

Class StudentInfo extends React. Component{

   constructor(props){

     super(props);

    }

    render(){

      return(

        <div className="main">

          <h2>{this.props.name}</h2>

          <h4>{this.props.rollNumber}</h4

        </div>

      )

    }

   }

 

As we can see in the code above, you can use this keyword in the case of class components.

State

  • Handling state

Functional components use React hooks to handle the state. It uses the state Hook to set the state of a variable inside the Component:

function ClassRoom(props){

   let [studentsCount,setStudentsCount] = useState(0);

    const addStudent = () => {

      setStudentsCount(++studentsCount);

   }

    return(

      <div>

        <p>Number of students in classroom: {studentsCount}</p>

        <button onClick={addStudent}>Add Student</button>

      </div>

    )

   }

Since state Hook returns an array of two items, the first item contains the current state, and the second is a function that you can use to update the form.

In the code above, using array destructuring, we have set the variable name to studentsCount with a current value of “0”. Also, setStudentsCount is the function that you can use to update the state.

For reading the state, we can also see from the code above the variable name that you can directly use to read the current state of the variable.

However, we cannot use React Hooks inside class components. Therefore state handling is done very differently in a class component:

Example

Let’s take the same above example and convert it into a class component:

Class ClassRoom extends React. Component{

        constructor(props){

            super(props);

            this.state = {studentsCount : 0};

            this.addStudent = this.addStudent.bind(this);

         }

            add student(){

            this.setState((prevState)=>{

               return {studentsCount: prevState.studentsCount++}

            });

         }

            render(){

             return(

               <div>

                 <p>Number of students in class room: {this.state.studentsCount}</p>

                 <button onClick={this.addStudent}>Add Student</button>

               </div>

             )

           }

         }

In the code above, we see we are using this. State to add the variable students count and set the value to “0”.

For reading the state, we are generally using this. State. Students count.

We need to first bind the addStudent function to update the state. Only then will we be able to use the setState function, which is used to update the state? 

12 . What is the virtual DOM? How does React use the virtual DOM to render the UI?

The virtual DOM (Document Object Model) is a key concept in React, serving as an abstraction of the actual DOM elements. React uses the virtual DOM to optimize and enhance the efficiency of UI updates. Here’s how it works:

  1. Representation of UI Components:
    • The virtual DOM is essentially a lightweight copy of the real DOM. It represents the structure of the UI components in a virtual tree form.
  2. Changes Detection:
    • When there is a change in the application state (due to user interaction, data updates, etc.), React creates a new virtual DOM tree representing the updated UI.
  3. Diffing Algorithm:
    • React then employs a process called “reconciliation” or “diffing.” It compares the newly created virtual DOM tree with the previous one to identify the differences, or “diffs,” between them.
  4. Minimizing DOM Manipulation:
    • Instead of directly updating the entire real DOM for each change, React determines the minimal set of DOM operations required to bring the actual DOM in sync with the virtual DOM.
  5. Batched Updates:
    • React batches these minimal changes and performs a single update to the real DOM. This batching reduces the number of manipulations and enhances overall performance.
  6. Efficient Rendering:
    • By selectively updating only the changed parts of the DOM, React ensures that rendering is more efficient, leading to improved application performance.

In essence, the virtual DOM acts as a intermediary step, allowing React to optimize the process of updating the UI by making the necessary changes in the most efficient manner possible. This approach contributes significantly to React’s reputation for high-performance user interfaces.

13 . Why was virtual DOM introduced? 

DOM manipulation is an integral part of any web application, but DOM manipulation is quite slow when compared to other operations in JavaScript. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes.

For example, consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. It is called inefficient updating.

To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

14 . Differences between controlled & uncontrolled components

Controlled and uncontrolled components are just different approaches to handling input from elements in React. 

Controlled Component

  • Controlled Component: In a controlled component, you can control the value of the input element is by React. We store the state of the input element inside the code, and by using event-based callbacks, any changes made to the input element will also reflect in the code.

When a user enters data inside the input element, it triggers the onChange function. We check whether the value entered is valid or invalid inside the code. If the value is valid, we change the state and re-render the input element with the new value.

Example of a controlled component:

function FormValidation(props) {

let [inputValue, setInputValue] = useState("");

let updateInput = e => {

  setInputValue(e.target.value);

};

return (

  <div>

    <form>

      <input type="text" value={inputValue} onChange={updateInput} />

    </form>

  </div>

);

}

As one can see in the code above, the value of the input element is determined by the state of the inputValue variable. Any changes made to the input element are handled by the updateInput function.

  • Uncontrolled Component: In an uncontrolled component, the value of the input element is managed through DOM. Input elements inside uncontrolled components work just like normal HTML input form elements.

The DOM handles the state of the input element. Whenever the value of the input element is changed, it doesn’t call event-based callbacks.

The updated data is shown directly whenever the user enters data inside the input field. To access the value of the input element, we can use ref.

Example of an uncontrolled component:

function FormValidation(props) {

let input value = React.createRef();

let handleSubmit = e => {

  alert(`Input value: ${inputValue.current.value}`);

  e.preventDefault();

};

return (

  <div>

    <form onSubmit={handleSubmit}>

      <input type="text" ref={inputValue} />

      <button type="submit">Submit</button>

    </form>

  </div>

);

}

As one can see in the code above, we are not using the onChange function to govern the changes made to the input element. Instead, we are using ref to access the value of the input element. 

15 . Explain React state and props.

Props State

  • Immutable Owned by its Component
  • Has better performance Locally scoped
  • Can pass to child components Writeable/Mutable
  • has setState() method to modify properties
  • Changes to state can be asynchronous

React State

  • Every Component in react has a built-in state object, which contains all the property values that belong to that Component.
  • In other words, the state object controls the behaviour of a component. Any change in the state object’s property values leads to the Component’s re-rendering.

16 . How to declare a state object?

To declare a state object in React, you typically use the useState hook or the class component’s this.state syntax. In functional components with hooks, you can declare a state object like this:

const [state, setState] = useState({ key: 'initialValue' });

In class components, you can declare a state object in the constructor:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { key: 'initialValue' };
  }
}

Using useState in functional components is the more modern approach, while the class component syntax is less common in newer codebases.

17 . How to use and update the state object?

Class Car extends React. Component {

constructor(props) {

  super(props);

  this.state = {

    brand: "BMW,"

    colour: "Black"

  };

}

change color() {

  this.setState(prevState => {

    return {colour: "Red"};

  });

}

render() {

  return (

    <div>

      <button onClick={() => this.change color()}>Change Color</button>

      <p>{this.state.color}</p>

    </div>

  );

}

}

As one can see in the code above, we can use the state by calling this.state.propertyName, and we can change the state object property using the setState method.

React Props

  • React Props

Every React component accepts a single object argument called props (which stands for “properties”). These props can be passed to a component using HTML attributes, and the Component accepts these props as an argument.

Using props, we can pass data from one Component to another.

Passing props to a component:

While rendering a component, we can pass the props as an HTML attribute:

<Car brand= "Mercedes"/>

The Component receives the props:

Class component:

Class Car extends React. Component {

constructor(props) {

  super(props);

  this.state = {

    brand: this. Props. brand,

    colour: "Black"

  };

}

}

In Functional Component:

function Car(props) {

let [brand, setBrand] = useState(props.brand);

}

As one can see in the code above, we can use the state by calling this.state.propertyName, and we can change the state object property using the setState method.

18 . Explain about types of side effects in React component.

There are two types of side effects in React component. They are:

  • Effects without Cleanup: This side effect will be used in use effect, which does not restrict the browser from screen update. It also improves the responsiveness of an application. A few common examples are network requests, Logging, manual DOM mutations, etc.
  •  Effects with Cleanup: Some of the Hook effects will require the cleanup after DOM is updated. For example, if you want to set up an external data source subscription, it requires cleaning up the memory. Else there might be a problem of memory leak. It is a known fact that React will carry out the cleanup of memory when the unmounting of components happens. But the effects will run for each render() method rather than any specific method. Thus we can say that before the execution of the effects succeeding time, React will also clean up effects from the preceding render.

19 . What is prop drilling in React?

Sometimes while developing React applications, there is a need to pass data from a component higher in the hierarchy to a deeply nested component. To pass data between such components, we pass props from a source component and keep passing the prop to the next Component in the hierarchy till we reach the deeply nested Component.

// Top-level component
function App() {
  const data = "Hello, Prop Drilling Example";
  return <ParentComponent data={data} />;
}

// Intermediate component
function ParentComponent({ data }) {
  return <ChildComponent data={data} />;
}

// Deeply nested child component
function ChildComponent({ data }) {
  return <div>{data}</div>;
}

In this example, data is passed from the App component to ChildComponent through ParentComponent, even though ParentComponent doesn’t use data. Prop drilling can be avoided by using React context or state management libraries like Redux to make data more easily accessible to deeply nested components, improving code maintainability.

The disadvantage of using prop drilling is that the components that should otherwise be unaware of the data have access to the data.

20 . What are error boundaries?

Introduced in version 16 of React, Error boundaries allow us to catch errors that occur in the render phase.

  • What is an error boundary?

Any component which uses one of the following lifecycle methods is considered an error boundary.

In what places can an error boundary detect an error?

  1. Render phase
  2.  Inside a lifecycle method
  3.  Inside the constructor

21 . Without using error boundaries:

Class CounterComponent extends React. Component{

constructor(props){

  super(props);

  this.state = {

    counter value: 0 }

  this.incrementCounter = this.incrementCounter.bind(this) }

incrementCounter(){

  this.setState(prevState => counterValue = prevState+1); }

render(){

  if(this.state.counter === 2){

    throw new Error('Crashed');

  }

  return(

    <div>

      <button onClick={this.incrementCounter}>Increment Value</button>

      <p>Value of counter: {this.state.counterValue}</p>

    </div>

  )

}

}

In the code above, when the counterValue equals 2, we throw an error inside the render method.

When not using the error boundary, we see a blank page instead of an error. Since any error inside the render method leads to unmounting of the Component. We use error boundaries to display an error inside the render method.

Error boundaries

With error boundaries: As mentioned above, an error boundary is a component using one or both methods: static getDerivedStateFromError and componentDidCatch.

Let’s create an error boundary to handle errors in the render phase:

Class ErrorBoundary extends React. Component {

constructor(props) {

  super(props);

  this.state = { hasError: false };

}

static getDerivedStateFromError(error) {     

  return { hasError: true }; 

}

 componentDidCatch(error, errorInfo) {       

  logErrorToMyService(error, errorInfo); 

}

render() {

  if (this.state.hasError) {     

    return <h4>Something went wrong</h4>     

  }

  Return this. Props. children;

}

}

In the code above, the getDerivedStateFromError function renders the fallback UI interface when the render method has an error.

componentDidCatch logs the error information to an error tracking service.

Now with the error boundary, we can render the CounterComponent in the following way:

<ErrorBoundary>

 <CounterComponent/>

</ErrorBoundary>

22 . What are React Hooks?

React Hooks are the built-in functions that permit developers to use the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. Each Component’s lifecycle has 3 phases: mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers to improve the reuse of code with higher flexibility in navigating the component tree.

Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now, using the use state Hook, we can keep the state in a functional component.

For example, the useState Hook lets you add state to a functional component. Here’s a simple example:

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

export default Counter;

In this example, useState creates a state variable count and a function setCount to update it. When the button is clicked, it triggers a re-render, updating the displayed count. Hooks like useState streamline state management in functional components, improving code organization and reusability.

23. Explain React Hooks.

What are Hooks? Hooks are functions that let us “hook into” React state and lifecycle features from a functional component.

React Hooks cannot be used in class components. They let us write components without class.

Why were Hooks introduced in React?

React hooks were introduced in the 16.8 version of React. Previously, functional components were called stateless components. Only class components were used for state management and lifecycle methods. The need to change a functional component to a class component whenever state management or lifecycle methods were used led to Hooks’s development.

Example of a hook: useState Hook:

In functional components, the useState Hook lets us define a state for a component:

function Person(props) {

// We are declaring a state variable called name.

// setName is a function to update/change the value of the name

let [name, setName] = useState('');

}

The state variable “name” can be directly used inside the HTML.

24 . What are the rules that must be followed while using React Hooks?

There are two rules which must be followed while you code with Hooks:

  • Only Call Hooks at the Top Level: React Hooks must be called at the top level of your custom component or within other hooks, not inside nested functions, loops, or conditionals. This ensures consistency in the order of execution.

Example:

function MyComponent() {
  // Good: Hooks called at the top level
  const [count, setCount] = useState(0);
  
  if (count === 0) {
    // Bad: Hook called conditionally
    const [data, setData] = useState(null);
  }

  return (
    // ...
  );
}
  •  Use Hooks in Functional Components: Hooks should only be used in functional components, not in class components. They allow you to manage state and side effects in functional components more easily.
  • Follow the Naming Convention: Hooks should start with “use” to signify that they are hooks. For example, useState, useEffect, and useCustomHook.
  • Don’t Skip Dependencies in useEffect: When using the useEffect hook, include all dependencies in the dependency array to ensure proper reactivity.

Example:

useEffect(() => {
  // Effect code here
}, [dependency1, dependency2]);

Create Custom Hooks for Reusable Logic: If you find yourself duplicating state and logic across multiple components, create custom hooks to encapsulate and reuse that logic.

function useCustomHook() {
  const [value, setValue] = useState(0);

  const increment = () => {
    setValue(value + 1);
  };

  return { value, increment };
}

Following these rules will help you use React Hooks effectively, leading to cleaner and more maintainable code in your React applications.

25 . What is the use of useEffect React Hooks?

The effect React Hook performs the side effects in functional components. With the help of useEffect, you will inform React that your Component requires something done after rendering the Component or after a state change. The function you have passed(“effect”) will be remembered by React and called after the performance of DOM updates is over. Using this, we can perform various calculations such as data fetching, setting up document titles, manipulating DOM directly, etc., that don’t target the output value. The effect Hook will run by default after the first render and after each Component update.

The useEffect React Hook will accept two arguments: useEffect(callback,[dependencies]);

The first argument callback represents the function having the logic of side-effect, and it will be immediately executed after changes are pushed to DOM. The second argument, dependencies, represents an optional array of dependencies. The effect () will execute the callback only if there is a change in dependencies between renderings.

26 . Why do React Hooks make use of refs?

Earlier, refs were only limited to class components, but now they can also be accessible in function components through the useRef Hook in React.

The refs are used for:

  • Managing focus, media playback, or text selection.
  •  Integrating with DOM libraries by third-party.
  •  Triggering the imperative animations.

27 . What are Custom Hooks?

A Custom Hook is a function in Javascript whose name begins with ‘use’ and calls other hooks. It is a part of React v16.8 hook update and also permits you to reuse the stateful logic without needing component hierarchy restructuring.

In almost all cases, custom hooks are sufficient for replacing render props and HoCs (Higher-Order components) and reducing the nesting required. Custom Hooks will also allow you to avoid multiple layers of abstraction or wrapper hell that might come with Render Props and HoCs.

However, the disadvantage of Custom Hooks is they cannot be used inside the classes.

React Interview Questions and Answers for Experienced

1 . Explain Strict Mode in React.

StrictMode is a tool added in version 16.3 of React to highlight potential problems in an application. It also performs additional checks on the application.

function App() {

 return (

   <React.StrictMode>

     <div classname="App">

       <Header/>

       <div>

         Page Content

       </div>

       <Footer/>

     </div>

   </React.StrictMode>

 );

}

To enable StrictMode, <React.StrictMode> tags need to be added inside the application:

import React from "react";

Write on next, import ReactDOM from "react-dom";

import App from "./App";

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

ReactDOM.render(

<React.StrictMode>

  <App />

</React.StrictMode>,

rootElement

);

StrictMode currently helps with the following issues:

  • Identifying components with unsafe lifecycle methods: Certain lifecycle methods are unsafe to use in asynchronous react applications. With third-party libraries, ensuring that certain lifecycle methods are also not used becomes difficult.
  •  StrictMode helps in providing us with a warning if any of the class components use an unsafe lifecycle method.
  •  Warning about legacy string API: If one uses an older version of React, callback ref is recommended to manage refs instead of using the string refs. StrictMode gives a warning if we are using string refs to manage refs.
  •  Warning about the usage of findDOMNode: Previously, the findDOMNode( ) method was used to search the tree of a DOM node. This method is deprecated in React. Hence, the StrictMode gives us a warning about the usage of this method.
  •  Warning about using legacy context API (because the API is error-prone).

2 . What are the different ways to style a React component?

There are many different ways through which one can style a React component. Some of the ways are :

  • Inline Styling: We can directly style an element using inline style attributes. Also, make sure the value of style is a JavaScript object:
Class RandomComponent extends React. Component {

 render() {

   return (

     <div>

       <h3 style={{ color: "Yellow" }}>This is a heading</h3>

       <p style={{ font-size: "32px" }}>This is a paragraph</p>

     </div>

   );

 }

}

Using JavaScript Object

Using JavaScript object: We can create a separate JavaScript object and set the desired style properties. This object can be also used as the value of the inline style attribute.

Class RandomComponent extends React. Component {

 paragraph styles = {

   colour: "Red,"

   font-size: "32px"

 };

 heading styles = {

   colour: "blue,"

   font-size: "48px"

 };

 render() {

   return (

     <div>

       <h3 style={this.headingStyles}>This is a heading</h3>

       <p style={this.paragraphStyles}>This is a paragraph</p>

     </div>

   ); }}

CSS Stylesheet: We can create a separate CSS file and write all the styles for the Component inside that file. This file needs to be imported inside the component file.

import './RandomComponent.css';

Class RandomComponent extends React. Component {

 render() {

   return (

     <div>

       <h3 className="heading">This is a heading</h3>

       <p className="paragraph">This is a paragraph</p>

     </div>

   );} }

CSS Modules: We can create a separate CSS module and also import this module inside our Component. Create a file with the “.module.css” ‘extension, styles.module.css:

.paragraph{

 colour: "red";

 border:1px solid black;

}

We can import this file inside the Component and use it:

import styles from ‘./styles.module.css’;

class RandomComponent extends React. Component {

render() {

   return (

     <div>

       <h3 className="heading">This is a heading</h3>

       <p className={styles.paragraph} >This is a paragraph</p>

     </div>

   );

 }

}

3 . Name a few techniques to optimize React app performance.

There are many ways through which one can optimize the performance of a React app;

Let us have a look

let’s have a look at some of them:

  • Using useMemo( ) is a React hook used for caching CPU-Expensive functions.
  • Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
    • Generally, useMemo( ) Hook can be used to cache such functions. Using useMemo( ), the CPU-Expensive function gets called when needed.
    •  Using React.PureComponent –It is a base component class that checks the state and also props of a component to know whether the Component should be updated.
    •  Instead of using the simple React. Component, we can use React.PureComponent that also reduces the re-renders of a component unnecessarily.
    •  Maintaining State Colocation is moving the state near where you need it.
    •  Sometimes in React app, we also have a lot of unnecessary states inside the parent component, making the code less readable and harder to maintain. Not to forget, having many states inside a single component also leads to unnecessary re-renders for the Component.
    •  Generally, It is better to shift states less valuable to the parent component to a separate component.
    •  Lazy Loading – Generally, It is a technique used to reduce the load time of a React app. Lazy loading also helps reduce the risk of web app performance to a minimum.

4 . How to pass data between react components ?

Parent Component to Child Component (using props)

With the help of props, we can also send data from a parent to a child component.

How do we do this?

Consider the following Parent Component:

import ChildComponent from "./Child";

   function ParentComponent(props) {

    let [counter, setCounter] = useState(0);

    let increment = () => setCounter(++counter);

    return (

      <div>

        <button onClick={increment}>Increment Counter</button>

        <ChildComponent counterValue={counter} />

      </div>

    );

   }

As one can see in the code above, we are also rendering the child component inside the parent component by providing a prop called counterValue. The counter’s value is also passed from the parent to the child component.

We can also use the data passed by the parent component in the following way:

function ChildComponent(props) {

return (

  <div>

    <p>Value of counter: {props.counterValue}</p>

  </div>

);

}

We also use the props.counterValue to display the data passed on by the parent component.

Child Component to Parent Component (using callbacks)

This one is a bit tricky. However, we can follow the steps below:

  • Create a callback in the parent component, which also takes in the data needed as a parameter.
  •  Also, pass this callback as a prop to the child component.
  •  Also, Send data from the child component using the callback.

We are considering the same example above, but we will pass the updated counter value from child to parent in this case.

Step1 and Step2: Create a callback in the parent component, and pass this callback as a prop.

function ParentComponent(props) {

let [counter, setCounter] = useState(0);

let callback = valueFromChild => setCounter(valueFromChild);

return (

  <div>

    <p>Value of counter: {counter}</p>

    <ChildComponent callbackFunc={callback} counterValue={counter} />

  </div>

);

}

As one can see in the code above, we created a function called callback which also takes in the data received from the child component as a parameter.

Next, we passed the function callback as a prop to the child component.

Step 3: Pass data from the child to the parent component. For example,

function ChildComponent(props) {

let childCounterValue = props.counterValue;

return (

  <div>

    <button onClick={() => props.callbackFunc(++childCounterValue)}>

      Increment Counter

    </button>

  </div>

);

}

In the code above, we have also used the props.counterValue and set it to a variable called childCounterValue.

Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc.

This way, we can also pass data from the child to the parent component. 

5 . What is Higher Order Components ?

Simply put, Higher-Order Component(HOC) is a function that takes in a component and also returns a new component.

When do we need a Higher Order Component?

While developing React applications, we might develop components similar to each other with minute differences. Developing similar components might not be an issue in most cases, but we must keep our code DRY while developing larger applications. Therefore, we want an abstraction that allows us to define this logic in a single place and share it across components. HOC allows us to create that abstraction.

6 . What are the different phases of the component lifecycle?

There are four different phases in the lifecycle of React component. They are:

  • Initialization: During this phase, React component will prepare by setting up the default props and initial state for the upcoming tough journey.
  •  Mounting: Mounting refers to putting the elements into the browser DOM. Since React uses VirtualDOM, the entire browser DOM currently rendered would not be refreshed. This phase includes the lifecycle methods componentWillMount and componentDidMount.
  •  Updating: In this phase, a component will be updated when there is a change in the state or props of a component. This phase will have lifecycle methods like componentWillUpdate, shouldComponentUpdate, render, and componentDidUpdate.
  •  Unmounting: In this last phase of the component lifecycle, the Component will be removed from the DOM or unmounted from the browser DOM. This phase will have the lifecycle method named componentWillUnmount.

7 . Lifecycle methods of React

React lifecycle hooks will have methods automatically called at different phases in the component lifecycle. Thus it provides good control over what happens at the invoked point. Generally, it provides the power to effectively control and manipulate what goes on throughout the component lifecycle.

For example, if you are developing a YouTube application, the application will use a network for buffering the videos, and it consumes the power of the battery (assume only these two). After playing the video, if the user switches to any other application, you should also ensure that the resources like network and battery are used most efficiently. You can stop or pause the video buffering, which stops the battery and network usage when the user switches to another application after video play.

So we can say that the developer will be able to produce a quality application with the help of lifecycle methods, and it also helps developers to make sure to plan what and how to do it at different points of birth, growth, or death of user interfaces.

The various lifecycle methods are:

  • Constructor (): This method will be called when the Component is initiated before anything has been done. It helps to set up the initial state and initial values.
  •  getDerivedStateFromProps(): This method will be called just before element(s) rendering in the DOM. It helps to set up the state object depending on the initial props. The getDerivedStateFromProps() method will have a state as an argument, and it also returns an object that made changes to the state. It will also be the first method to be called on an update of a component.
  •  Render (): This method will output or re-render the HTML to the DOM with new changes. The render() method is also essential and will always be called, while the remaining methods are optional and will be called when they are defined.
  •  componentDidMount(): This method will be called after the Component’s rendering. Using this method, you can generally run statements that need the Component to be already kept in the DOM.
  •  shouldComponentUpdate(): This method will return the Boolean value, which will specify whether React should proceed further with the rendering. The default value for this method will be True.
  •  getSnapshotBeforeUpdate(): This method will provide access to the props as well as to the state before the update. It is possible to check the previously present value before or after the update.
  •  componentDidUpdate(): This method will be called after the Component has been updated in the DOM.
  •  component will unmount (): This method will be called when the component removal from the DOM is about to happen.

8 . Does React Hook work with static typing?

Static typing refers to the process of code check during compilation to ensure all variables will be statically typed. React Hooks are functions designed to ensure that all attributes must be statically typed. To enforce stricter static typing within our code, we can also use the React API with custom Hooks.

Types of Hooks in React

There are two types of Hooks in React. They are:

Built-in Hooks

1. Built-in Hooks: The built-in Hooks are generally divided into two parts as given below:

  • Basic Hooks:useState(): Use it to set and also retrieve the state.
  •  use effect (): It enables performing the side effects in the functional components.
  •  useContext(): Use it for creating common data that is to be accessed by the components hierarchy without having to pass the props down to each level.
  •  Additional Hooks:useReducer(): Use it when a complex state logic has several sub-values or when the upcoming state is dependent on the previous state. It will also enable you to optimize component performance, which will also trigger deeper updates as it permits to pass the dispatch down instead of callbacks.
  •  useMemo(): Use it for recomputing the memoized value when there is a change in one of the dependencies. This optimization will help to avoid expensive calculations on each render.
  •  use callback (): This is useful while passing callbacks into the optimized child components and depends on the equality of reference for the prevention of unneeded renders.
  •  useImperativeHandle(): It will enable modifying the instance that will pass with the ref object.
  •  useDebugValue(): Generally, it displays a label for custom hooks in React DevTools.
  •  useRef(): It will permit creating a reference to the DOM element directly within the functional Component.
  •  useLayoutEffect(): Use it for the reading layout from the DOM and also re-rendering synchronously.

Custom Hooks

2. Custom Hooks: A custom Hook is a function of JavaScript. The Custom Hook working is similar to a regular function. The “use” at the beginning of the Custom Hook Name is required for React to understand that this is a custom Hook, and also it will describe that this specific function follows the rules of Hooks. Moreover, developing custom Hooks will enable you to extract component logic from within reusable functions.

9 . Differentiate React Hooks vs. Classes.

React Hooks Classes

It is used in functional components of React. It is generally popular in class-based components of React.

Also, it will not require a declaration of any kind of constructor. It is necessary to declare the constructor inside the class component.

Also, it does not require the use of this keyword in state declaration or modification. The keyword this will be used in state declaration (this. state) and also modification (this.setState()).

It is easier to use because of the state functionality. No specific function is available to help us to access the state and its corresponding setState variable.

React Hooks can help implement Redux and context API. Because of the long setup of state declarations, class states are generally not preferred.

10 . How will the performance of using Hooks differ in comparison with the classes?

  • React Hooks will avoid a lot of overheads, such as the instance creation, binding of events, etc., that are present with classes.
  •  Hooks in React will result in smaller component trees. They will avoid the nesting that exists in HOCs (Higher Order Components). Also, render props result in less work.

11 . Do Hooks cover all the functionalities provided by the classes?

We aim for Hooks to cover all the functionalities for classes at its earliest. There are no Hook equivalents for the following methods that are not introduced in Hooks yet:

  • getSnapshotBeforeUpdate()
  •  getDerivedStateFromError()
  •  componentDidCatch()

Since it is an early time for Hooks, a few third-party libraries may not be compatible with Hooks, but they will be added soon.

12 . What is React Router?

React Router refers to the standard library used for routing in React. It permits us to build a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change of the browser URL and keeps the user interface in sync with the URL. React Router will also use the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, including and using this package is unnecessary. Any other compatible routing library would also work with React.

The major components of React Router are given below:

  • BrowserRouter: It is a router implementation that will use the HTML5 history API (pushState, pop state, and event replaceState) to keep your UI in sync with the URL. However, it is the parent component useful in storing all other components.
  •  Routes: It is a newer component introduced in the React v6 and is an upgrade of the Component.
  •  Route: It is considered a conditionally shown component, and some UI will be rendered by this whenever there is a match between its path and the current URL.
  •  Link: It is useful in creating links to various routes and implementing navigation throughout the application. It works similarly to the anchor tag in HTML.

13 . Can React Hook replaces Redux?

The React Hook cannot be considered a replacement for Redux. It is an open-source, JavaScript library useful in managing the application state when it comes to the management of the global application state tree in large complex applications, even though the React will provide a seducer hook that manages state transitions similar to Redux. Redux is very useful at a lower level of component hierarchy to handle the pieces of a state dependent on each other instead of a declaration of multiple useState hooks.

The complexity will be high in larger commercial web applications, and using only React Hook may not be sufficient. Few developers will also try to tackle the challenge with the help of React Hooks, and others will combine React Hooks with Redux.

14 . Explain conditional rendering in React.

Conditional rendering refers to the dynamic output of user interface markups based on a condition state. It works in the same way as JavaScript conditions. Using conditional rendering, it is possible to toggle specific application functions, API data rendering, hide or show elements, decide permission levels, authentication handling, and so on.

There are different approaches for implementing conditional rendering in React. Some of them are:

  • Using if-else conditional logic, which is suitable for smaller as well as medium-sized applications
  •  Using ternary operators, which also takes away some amount of complication from if-else statements
  •  Using element variables, which will enable us to write cleaner code.

15 . Create a simple React Hooks example program

I will assume that you have some coding knowledge about JavaScript and have installed Node on your system for creating the below given React Hook program. An installation of Node also comes with the command-line tools: npm and npx, where npm is useful to install the packages into a project, and npx is useful in running Node commands from the command line. However, the next looks in the current project folder is to check whether ayou can install a command. When the command is unavailable on your computer, the npx will also look in the npmjs.com repository. Load the latest version of the command script and also run without locally installing it. This feature is also useful in creating a skeleton React application within a few key presses.

Understand It Better

Open the Terminal inside the folder of your choice, and run the following command:

npx create-react-app react-items-with-hooks

Here, the create-react app is an app initializer created by Facebook to help with the easy and also quick creation of React application. It also provide options to customize it while creating the application. The above command will also create a new folder popular as react-items-with-hooks that you can initialize with a basic React application. Now, you can also open the project in your favourite IDE. You can see an src folder inside the project along with the main application component App.js. This file also has a single function, App(), which will return an element and use an extended JavaScript syntax(JSX) for defining the Component.

JSX will permit you to write HTML-style template syntax directly into the JavaScript file. Moreover, you can convert this mixture of JavaScript and HTML by React toolchain into pure JavaScript that will render the HTML element.

Also, you can define your React components by writing a function that will return a JSX element.

For Example

You can try this by creating a new file, src/SearchItem.js, and putting the following code into it.

import React from 'react';

export function SearchItem() {

 return (

   <div>

     <div className="search-input">

       <input type="text" placeholder="SearchItem"/>

     </div>

     <h1 className="h1">Search Results</h1>

     <div className="items">

       <table>

         <thead>

           <tr>

             <th className="itemname-col">Item Name</th>

             <th className="price-col">Price</th>

             <th className="quantity-col">Quantity</th>

           </tr>

         </thead>

         <tbody></tbody>

       </table>

     </div>

   </div>

 );

}

It is all about how you can create a component. It will only display the empty table and also doesn’t do anything. But you will be able to use the Search component in the application.

Understand it better

You can also open the file src/App.js and add the import statement given below to the top of the file.

import { SearchItem } from './SearchItem';

Now, from the logo.svg, you can remove the import. Also, you can replace the contents of return-ed value in the function App() with the following code:

<div className="App">

 <header>

   Items with Hooks

 </header>

 <SearchItem/>

</div>

You can notice that <SearchItem/> has been used similarly to an HTML element. The JSX syntax will also enable for inclusion of the components in this approach directly within the JavaScript code. Also, test your app by running the below-given command in your Terminal.

npm start

This command will also compile your application and open your default browser into http://localhost:4000.

This application will work finely, but it doesn’t look nice as it doesn’t react to any input from the user. You can also make it more interactive by adding a state with React Hooks, adding authentication, etc.

13 . How to create a switching component for displaying different pages?

A switching component refers to a component that will render one of the multiple components. We should also use an object for mapping prop values to components.

A below-given example will also show you how to display different pages based on page prop using the switching component:

import HomePage from ‘./HomePage.’

Write on next, import AboutPage from ‘./AboutPage.’

import FacilitiesPage from ‘./FacilitiesPage.’

Now, write import ContactPage from ‘./ContactPage’

import HelpPage from './HelpPage.'

const PAGES = {

 home: HomePage,

 about: AboutPage,

 facilities: FacilitiesPage,

 contact: ContactPage

 help: HelpPage

}

const Page = (props) => {

 const Handler = PAGES[props.page] || HelpPage

 return <Handler {...props} />

}

// The PAGES object keys can be used in prop types to catch dev-time errors.

Page.propTypes = {

 page: PropTypes.oneOf(Object.keys(PAGES)).isRequir

14 . How to re-render the view when the browser is resized?

It is possible to listen to the resize event in componentDidMount() and then update the width and height dimensions. It also requires the removal of the event listener in the Component will unmount () method.

Using the below-given code, we can also render the view when the browser is resized.

Class WindowSizeDimensions extends React. Component {

 constructor(props){

   super(props);

   this.updateDimension = this.updateDimension.bind(this);

 }

 componentWillMount() {

   this.updateDimension()

 }

 componentDidMount() {

   window.addEventListener('resize,' this.updateDimension)

 }

 componentWillUnmount() {

   window.removeEventListener('resize,' this.updateDimension)

 }

 updateDimension() {

   this.setState({width: window.innerWidth, height: window.innerHeight})

 }

 render() {

   return <span>{this.state.width} x {this.state.height}</span>

 }

}

15 . How to pass data between sibling components using React router?

Passing data between sibling components of React is possible using React Router with the help of history.push and match.params.

For example, in the code given below, we have a Parent component AppDemo.js, and two Child Components, HomePage and AboutPage. You must also keep everything inside a Router by using React-router Route. It is also having a route for /about/{params} where we will pass the data.

For Example

import React, { Component } from ‘react’;

class AppDemo extends Component {

render() {

  return (

    <Router>

      <div className="AppDemo">

      <ul>

        <li>

          <NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink>

        </li>

        <li>

          <NavLink to="/about" activeStyle={{ color:'blue' }}>About

 </NavLink>

        </li>

 </ul>

             <Route path="/about/:aboutId" component={AboutPage} />

             <Route path="/about" component={AboutPage} />

             <Route path="/" component={HomePage} />

      </div>

    </Router>

  );

}

}

export default AppDemo;

Moreover, the HomePage is a functional component with a button. On button click, we are also using props. history.push(‘/about/’ + data) to programmatically navigate into /about/data.

export default function HomePage(props) {

 const handleClick = (data) => {

  props. history.push('/about/' + data);

 }

return (

  <div>

    <button onClick={() => handleClick('DemoButton')}>To About</button>

  </div>

)

}

Also, the functional Component AboutPage will obtain the data passed by props.match.params. about.

export default function AboutPage(props) {

if(!props.match.params.aboutId) {

    return <div>No Data Yet</div>

}

return (

  <div>

    {`Data obtained from HomePage is ${props.match.params.aboutId}`}

  </div>

)

}

16 . How to perform automatic Redirect after login?

In React, performing an automatic redirect after login can be achieved by using the react-router-dom library. This library provides a Redirect component that can be used to navigate to a different route.

Assuming you have a route set up for the login page, you can use the useHistory hook from react-router-dom to programmatically navigate to another route after a successful login.

for example:

  1. Install react-router-dom if you haven’t already:
npm install react-router-dom

Assuming you have a component for your login page, you can use the useHistory hook to redirect after a successful login. Here’s an example:

// Import necessary dependencies
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';

// Your login component
const LoginPage = () => {
  // State to manage login credentials
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  // useHistory hook to get access to the history object
  const history = useHistory();

  // Function to handle login
  const handleLogin = () => {
    // Perform your login logic here

    // Assuming login is successful, redirect to another route
    // For example, redirect to the home page
    history.push('/home');
  };

  return (
    <div>
      {/* Your login form */}
      <form>
        <label>
          Username:
          <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
        </label>
        <br />
        <label>
          Password:
          <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
        </label>
        <br />
        <button type="button" onClick={handleLogin}>
          Login
        </button>
      </form>
    </div>
  );
};

export default LoginPage;

In this example, after a successful login, the handleLogin function is called, and it uses the history.push('/home') method to navigate to the ‘/home’ route. Adjust the route according to your application structure.

Make sure you have set up your routes appropriately using react-router-dom in your main application file or wherever your routes are defined.

17 . How do you display data from MongoDB using React JS?

To display data from MongoDB using React.js, you typically follow these general steps:

  1. Set Up Your MongoDB Database:
    • Make sure you have MongoDB installed and running.
    • Create a database and a collection to store your data.
  2. Create a Node.js/Express.js Backend:
    • Set up a Node.js/Express.js server to connect to your MongoDB database.
    • Use a MongoDB driver like Mongoose to interact with the database.
    • Create routes to handle CRUD operations (Create, Read, Update, Delete).
  3. Build API Endpoints:
    • Define API endpoints for fetching data from MongoDB.
    • For example, you might have an endpoint like /api/data that retrieves data from the database.
  4. Install Necessary Dependencies:
    • In your React.js project, install Axios or another HTTP client library to make API requests.
npm install axios

Make API Requests from React:

  • In your React component, use useEffect or another lifecycle method to make an HTTP request to your API endpoint.
  • Use Axios or another library to handle the API request. Here’s a basic example using Axios:
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const YourComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get('/api/data');
        setData(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []); // The empty dependency array ensures the effect runs once after the initial render.

  return (
    <div>
      {data.map(item => (
        <div key={item._id}>{item.fieldName}</div>
        // Replace "fieldName" with the actual field you want to display
      ))}
    </div>
  );
};

export default YourComponent;
  1. Render Data in Your React Component:
    • Map through the data array and render the desired information in your React component.
  2. Style and Enhance:
    • Apply styles and enhance the display of your data as needed.

Remember to replace /api/data with the actual endpoint you’ve set up in your Express.js backend. Additionally, make sure your Express.js server is running while you’re developing your React application.

This is a simplified example, and in a real-world scenario, you might want to add error handling, loading indicators, and more depending on your application’s requirements.