react js

react interview question | react interview question and answers | react interview question for senior developer | top react interview question | interview question react | interview question react js | react interview questions

💡 What is the difference between PureComponent and component?

React.PureComponent is similar to React.Component. The difference between them is that React. A component doesn’t implement, but React.PureComponent implements it with a shallow prop and state comparison.
PureComponent will do a shallow comparison on both props and state when they changed while Component won’t compare current props and state. Thus, the component will re-render by default whenever shouldComponentUpdate is called.

✔ You should go for React.PureComponent when you can satisfy any of the below conditions.

  • State/Props should be an immutable object
  • State/Props should not have a hierarchy
  • You should call forceUpdate when data changes

✔ Let’s say that we have a component tree with a three-level hierarchy: parent, children, and grandchildren.

When the parent’s props are changed in a way that the props of only one child are changed, then:

  • If all components are regular components, then the entire component tree will rerender.
  • If all children and grandchildren are pure components, then only one child will rerender, and one or all of its grandchildren, depending on whether their props are changed. If there are many components in this component tree, it may mean a significant performance boost.

💡 What are the advantages to use Pure Components?

Extending React Class Components with Pure Components ensures the higher performance of the Component and ultimately makes your application faster, While in the case of Regular Component, it will always re-render the value of State and Props changes or not.
Since Pure Components restricts the re-rendering when there is no use for re-rendering of the component. Pure Components are Class Components that extend React.PureComponent.

💡 Any example of HOC in React APIs?

React.memo is a higher-order component.

💡 How do we pass data between components in react?

For passing data from parent to child component, we use props. Props data is sent by the parent component and cannot be changed by the child component as they are read-only.

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component. The child component calls the parent callback function using props and passes the data to the parent component.
For passing data among siblings, there are multiple methods we can choose from as shown below:

  • Combination of the above two methods (callback and use of props).
  • Using Redux.
  • ContextAPI

💡 Explain How React ref differs depending on the type of the node?

  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.
  • When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.
  • You may not use the ref attribute on function components because they don’t have instances. You can, however, use the ref attribute inside a function component.

💡 How can we use ref with functional components?

If you want to allow people to take a ref to your function component, you can use forwardRef (possibly in conjunction with useImperativeHandle), or you can convert the component to a class. 

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

React Interview Questions & Answers

💡 What is forwardRef?

ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.

React.forwardRef((props, ref) => {})
// Wrap Functional component with ForwardRef.

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
// Wrap class component with ForwardRef

const Counter = React.forwardRef((props, ref) => {
  class Counter extends React.Component {
    constructor(props) {
      this.state = {
        count: 0
    render() {
      return (
          Count: {this.state.count}
          <button ref={ref} onClick={() => this.setState(
            { count: this.state.count + 1 })}>
  return <Counter />

💡 What is React.Lazy?

  • React.lazy allows you to render dynamic imports as regular components. When this component is rendered for the first time, this will automatically load the bundle that contains the OtherComponent.
  • The lazy component should then be rendered inside a Suspense component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.
import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />

💡 What are all methods provided by React DOM API?

A React DOM package provides DOM-specific methods that can be applied at the top level of a web app in order to enable an efficient way of managing DOM elements.

  • render()
  • findDOMNode()
  • unmountComponentAtNode()
  • hydrate()
  • createPortal()


It renders a single component or several components grouped together in a component or div element. This function returns a reference to the component or null if a stateless component was rendered.

ReactDOM.render(element, container, callback)

💡 What is the difference between ReactDOM.render vs React Component render?


A component’s render() method takes no arguments and returns the corresponding React element tree for that component. Component.render() gets called when the props or the state of a component changes and shouldComponentUpdate() return true. Based on the new props and state a new React element tree is returned from the Component.render() method.


The ReactDOM.render(element, container) method is a top-level API that takes a React element root of an element tree and a container DOM element as arguments. It then turns that passed React element into a corresponding DOM element (tree) and then mounts that element as a child in the container DOM element.
ReactDOM.render(element, container, callback)

💡 What are the advantages of using Axios in react?

  1. It comes with useful settings for working with JSON data. You don’t always need to set your headers, unlike with other APIs like the Fetch API.
  2. Axios has function names that match any HTTP methods. To perform a GET request, you use the .get() method.
  3. Axios accomplishes more with fewer lines of code. Unlike the Fetch API, you only need one .then() callback to access your requested JSON data.
  4. Axios handles errors better. Axios will offer you 400 and 500-range errors. Unlike the Fetch API, which requires you to manually check the status code and throw an error.
  5. Axios can be used on both the client and the server.

💡 What are the advantages of Axios interceptor?

Axios interceptors are the default setups that are automatically appended to every request or response received by a user.

// Add a request interceptor
  config => {
    const token = service.getToken() // get token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    config.headers['Content-Type'] = 'application/json';
    return config;
  error => {

// response
  response => {
    return response
  error => {
    // handle errors
      const status = error.response.status;
      const originalRequest = error.config;
     return Promise.reject(error);

💡 How do you know if a component is mounted or unmounted?

We can use useEffect hook to check this. We created a state variable and set this to true inside useEffect callback. If it’s true means the component is mounted. And inside the effect cleanup function, set this state variable to false. This means at this point, the component is unmounted.

import React, { useEffect, useState } from "react";

export default function App() {
  const [isMounted, setIsMounted] = useState(false);	

  useEffect(() => {
    return () => setIsMounted(false);
  }, []);
  return <div>{isMounted.toString()}</div>;

React Interview Questions & Answers

💡 What is wrong with the below code?


        this.state ={
            isEditMode: false,
            applyCode: props.applyCode

If the props are changed without refreshing the component, the new prop value will never be assigned to the state’s applyCode. This is because the constructor function is only called when the Component is first created.
So don’t initialize the state with props that can be changed later. Instead, use props directly in the component.
You can use static getDererivedStateFromProps() to update the state when props change.

💡 What is the second argument of setState method?

The setState function takes an optional callback parameter that can be used to make updates after the state is changed. This function will get called once the state has been updated, and the callback will receive the updated value of the state.
The setState callback’s use case is fairly obvious. When you want a function to run after a specific state has been updated, you use this technique.
If you put this function in render() instead, This function will execute every time any state is modified.

💡 Is setState async or sync?

This function is used to update the state of a component, but it’s important to remember that setState is asynchronous. It doesn’t update the state object immediately. If you want to perform a check or some other action based on the most recent update, using the setState() callback is a good practice.

💡 Can you await this setState?

No. It’s not the right way to use await in front of setstate function. If you want to do an async operation, put it in a separate thread and using the callback function update the setstate function.

React Interview Questions & Answers

💡 What to use instead of setState in React?

useReducer() is a method from the React Hooks API, similar to useState but gives you more control to manage the state.

💡 What is the difference between setState and render()?

render() method will run every time the state is updated, whereas a setState() callback will only run after updating the specific value in the state.

💡 What is the difference between the redux dispatch function and useReducer hook dispatch?

useReducer function is tightly coupled to a specific reducer. We dispatch action objects to that reducer only, whereas, in Redux, the dispatch function sends the action object to the store.
In the case of redux, At the time of dispatch, the components don’t need to know which reducer will process the action.

💡 What is the meaning of batching in React?

Batching is when React groups multiple state updates into a single re-render for better performance.
In React, batching helps to reduce the number of re-renders that happen when a state changes, when you call setState.
Before Version 18, React batched state updates in event handlers only, not in callbacks or in any promises. React 18 introduces automatic batching which allows all state updates – even within promises, setTimeouts, and event callbacks – to be batched.

const handleClick = () => {

For the above event handling, re-rendered will occur once at the end. But If we put these inside any promise, rendering will be 3 times.

💡 Have you used flushSync in React?

// Without flushAsync
const onAddNew = (newTodoItem) => {
	setTodos([...todos, { task: newTodoItem }]);
	 myListRef.current.scrollTop = myListRef.current.scrollHeight;

Suppose we want to update the scroll height of the list container to the end position when any new item is added to that list. So If you simply put the scrolling logic inside the handler, you will not get the expected result on UI. Because setTodos is not synchronous, what happens here is, scroll code runs first, and then the todos actually get updated.
So, to get it working as expected we would have to make sure that the logic for scrolling runs only after the todos state has been updated. And that’s where flushSync comes in handy.

// Use flushAsync
const onAddNew = (newTodoItem) => {
	  flushSync(() => {
		setTodos([...todos, { task: newTodoItem }]);

	  myListRef.current.scrollTop = myListRef.current.scrollHeight;

To use flushSync, we need to import it from react-dom:
import { flushSync } from "react-dom";

Now we have made sure that the state update happens synchronously and the logic for scrolling is executed only after the state has been updated.

react interview question | react interview question and answers | react interview question for senior developer | top react interview question | interview question react | interview question react js | react interview questions

Leave a Reply

Your email address will not be published.