interview

Top reactjs questions asked in interview

21 min read
#interview

What is react Js?

React is an open-source front-end JavaScript library that is used for building user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps.


What are the main features of react?

The major features of React are:

  • React uses JSX syntax, a syntax extension of javascript that allows developers to write HTML in their JS code.
  • React uses Virtual DOM instead of RealDOM considering that RealDOM manipulations are expensive.
  • Supports server-side rendering.
  • React follows Unidirectional data flow or data binding.
  • Uses reusable/composable UI components to develop the view.
  • React can be used to build web as well as mobile application.

What is JSX?

JSX is a XML-like syntax extension to ECMAScript. Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.

export default function App() {
  return (
    <div>
      <h1>Welcome to React world!</h1>
    </div>
  );
}

The above react code can be written in plain javascript like below

React.createElement("div", null, React.createElement("h1", null, "Welcome to React world!\""));

What is the difference between Element and Component?

An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.

The object representation of React Element would be as follows:

const element = React.createElement("div", { id: "login-btn" }, "Login");

The above React.createElement() function returns an object:

{
  type: 'div',
  props: {
    children: 'Login',
    id: 'login-btn'
  }
}

And finally it renders to the DOM using ReactDOM.render():

<div id="login-btn">Login</div>

Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:

const Button = ({ onLogin }) => (
  <div id={"login-btn"} onClick={onLogin}>
    Login
  </div>
);

Then JSX gets transpiled to a React.createElement() function tree:

const Button = ({ onLogin }) =>
  React.createElement(
    "div",
    { id: "login-btn", onClick: onLogin },
    "Login"
  );

How to create components in React?

There are two possible ways to create a component.

Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the first parameter and return React elements:

function Greeting({ message }) {
  return <h1>{`Hello, ${message}`}</h1>;
}

Class Components: You can also use ES6 class to define a component. The above function component can be written as:

class Greeting extends React.Component {
  render() {
    return <h1>{`Hello, ${this.props.message}`}</h1>;
  }
}

After the introduction of React Hooks in react, class based components are hardly used.


What are Pure Components in Reactjs?

In functional programming, A function is considerd to be pure when

  • Its return value is only determined by its input values
  • Its return value is always the same for the same input values

In react a component is said to be pure when it renders the same output for the same state and props. For class based component, React provides the PureComponent base class. Class components that extend the React.PureComponent class are treated as pure components.

Pure components have some performance improvements and render optimizations since React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state.

Are React functional components pure?

Functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since by definition, they are not classes, so they are not pure component.

If you want React to treat a functional component as a pure component, you’ll have to convert the functional component to a class component that extends React.PureComponent.

With React.memo(), you can create memoized functional components that bail out of rendering on unnecessary updates using shallow comparison of props.

Using the React.memo() API, the previous functional component can be wrapped as follows:

import { memo } from "react";
const Todos = ({ todos }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};
export default memo(Todos);

For one, React.memo() is a higher-order component. It takes a React component as its first argument and returns a special type of React component that allows the renderer to render the component while memoizing the output. Therefore, if the component’s props are shallowly equal, the React.memo() component will bail out the updates.

React.memo() works with all React components. The first argument passed to React.memo() can be any type of React component. However, for class components, you should use React.PureComponent instead of using React.memo(). React.memo() also works with components rendered from the server using ReactDOMServer.


What is state in React?

State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.

Let's create a user component with message state,

import React, { useState } from "react";
function User() {
  const [message, setMessage] = useState("Welcome to React world");
  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}

What are props in React?

Props are inputs to components. They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes. They are data passed down from a parent component to a child component.

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

  • Pass custom data to your component.
  • Trigger state changes.
  • Use via this.props.reactProp inside component's render() method.

For example, let us create an element with reactProp property:

<Element reactProp={"1"} />

This reactProp (or whatever you came up with) name then becomes a property attached to React's native props object which originally already exists on all components created using React library.

props.reactProp

Example: Props in Class Based Component

import React from "react";
import ReactDOM from "react-dom";

class ChildComponent extends React.Component {
  render() {
    return (
      <div>
        <p>{this.props.name}</p>
        <p>{this.props.age}</p>
      </div>
    );
  }
}

class ParentComponent extends React.Component {
  render() {
    return (
      <div>
        <ChildComponent name="John" age="30" />
        <ChildComponent name="Mary" age="25" />
      </div>
    );
  }
}

Example: Props in Functional Component

import React from "react";
import ReactDOM from "react-dom";

const ChildComponent = (props) => {
  return (
    <div>
      <p>{props.name}</p>
      <p>{props.age}</p>
    </div>
  );
};

const ParentComponent = () => {
  return (
    <div>
      <ChildComponent name="John" age="30" />
      <ChildComponent name="Mary" age="25" />
    </div>
  );
};

What is the difference between state and props?

Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component.

Example of State:

import React from 'react';
function Counter() {
  const [count, setCount] = React.useState(1);  <-- React State
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
} 
export default Counter;

Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.

Example of props:

function Avatar({ person, size }) {
  return (
    <img
      className="avatar"
      src="https://i.imgur.com/1bX5QH6.jpg"
      alt="Lin Lanying"
      width={100}
      height={100}
    />
  );
}
export default function Profile() {
  return (
    <Avatar 
    person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}
    size={100}
    />
  );
}

What is the use of key prop in reactjs?

A key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.

Keys should be unique among its siblings. Most often we use ID from our data as key:

const todoItems = todos.map((todo) => <li key={todo.id}>{todo.text}</li>);

When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) => (
  <li key={index}>{todo.text}</li>
));

Note:

  • Using indexes for keys is not recommended if the order of items may change. This can negatively impact performance and may cause issues with component state.
  • If you extract list item as separate component then apply keys on list component instead of li tag.
  • There will be a warning message in the console if the key prop is not present on list items.

What is React Hooks?

React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components

Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility 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 useState hook, we can keep the state in a functional component.

  • useState: It declares a state variable that you can update directly.
  • useReducer: It declares a state variable with the update logic inside a reducer function.
  • useContext: It reads and subscribes to a context.
  • useRef declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node.
  • useImperativeHandle lets you customize the ref exposed by your component. This is rarely used.
  • useEffect connects a component to an external system.
  • useMemo lets you cache the result of an expensive calculation.
  • useCallback lets you cache a function definition before passing it down to an optimized component.

What is the use of React state Hooks?

React State lets a component remember information so that you can use it latter. In below example, we are defining a react state using useState and holding a initial value 0.

useState returns an array containing two value. The first one is current state and second one is a function which lets you change the state.

The set function set the new state and whenever a state is updated , component gets re-renderd.

import {useState} from "react"
export default function Counter() {
  const [count, setCount] = useState(0); // <--- react state
  return (
    <div>
      <h1>Hello react</h1>
      <h1>{count}</h1>
      <button onClick={()=>setCount(prev=>prev+1)}>Increase Count</button>
    </div>
  )
}

set function can directly set a new state to new value

setCount(count+1)

What is the use of useEffect Hooks in reactjs?

useEffect lets you invokes side effects from within functional components.

what is side effects?

A side effect is anything that affects something outside the scope of the function being executed. These can be a network request, which has your code communicating with a third party api, timer function like setTimeout.

useEffect is the hooks that lets you decouple the logic of rendering from side effects. Below code show data fetching side effects from an api. useEffect() starts a fetch request by calling fetchPosts() async function after the initial rendering. When the request completes, setPosts(posts) updates the posts state with the just fetched posts list.

import { useEffect, useState } from 'react';
function FetchPost() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    async function fetchPosts() {
      const response = await fetch('/posts');
      const posts = await response.json();
      setPosts(posts);
    }
    fetchPosts();
  }, []);
  return (
    <div>
      {posts.map(post => <div>{post}</div>)}
    </div>
  );
}

useEffect needs two arguments

  • A setup function which perform the side efects logic. It should return a cleanup function.
  • A list of dependencies including every value from your component used inside of those functions. React calls your setup and cleanup functions whenever it’s necessary, which may happen multiple times:

Setup code runs when component is added to the page (mounts). After every re-render of component where the dependencies have changed:

  • First, cleanup code runs with the old props and state.
  • Then, setup code runs with the new props and state.
  • cleanup code runs one final time after your component is removed from the page (unmounts).
useEffect(setup, dependencies?)

What is the use of useContext Hooks in reactjs?

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

useContext reads and subscribes to a context.

import {createContext} from "react"

import React from 'react';
 
// Creating the context object and passing the default values.
const authContext = createContext({status:null,login:()=>{}});
 
export default authContext;

import React, { useState } from "react";
import Auth from "./Auth";
import AuthContext from "./auth-context";
 
const App = () => {
  //using the state to dynamicallly pass the values to the context
  const [authstatus, setauthstatus] = useState(false);
  const login = () => {
    setauthstatus(true);
  };
  return (
    <React.Fragment>
      <AuthContext.Provider value={{ status: authstatus, login: login }}>
        <Auth />
      </AuthContext.Provider>
    </React.Fragment>
  );
};
export default App;

import React, { useContext } from "react";
import AuthContext from "./auth-context";
 
const Auth = () => {
  // Now all the data stored in the context can
  // be accessed with the auth variable
  const auth = useContext(AuthContext);
  console.log(auth.status);
  return (
    <div>
      <h1>Are you authenticated?</h1>
      {auth.status ?<p>Yes you are</p>:<p>Nopes</p>}
      <button onClick={auth.login}>Click To Login</button>
    </div>
  );
};
export default Auth;

What is the use of useRef Hooks in reactjs?

Refs let a component hold some information that isn’t used for rendering, like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an “escape hatch” from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.

useRef declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node. useImperativeHandle lets you customize the ref exposed by your component. This is rarely used.

const ref = useRef(initialValue)

Parameters initialValue: The value you want the ref object’s current property to be initially. It can be a value of any type. This argument is ignored after the initial render. Returns useRef returns an object with a single property:

current: Initially, it’s set to the initialValue you have passed. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property. On the next renders, useRef will return the same object.

import { useRef } from 'react';

export default function Counter() {
  let ref = useRef(0);
  function handleClick() {
    ref.current = ref.current + 1;
    alert('You clicked ' + ref.current + ' times!');
  }
  return (
    <button onClick={handleClick}>
      Click me!
    </button>
  );
}

What is the use of useMemo Hooks in reactjs?

useMemo is a React Hook that lets you cache the result of a calculation between re-renders.

const cachedValue = useMemo(calculateValue, dependencies)

useMemo takes two parameters, the first one is the function calculating the value that you want to cache and second one is dependencies.

  • calculateValue: The function calculating the value that you want to cache. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On subsequent renders, React will return the same value again if the dependencies have not changed since the last render. Otherwise, it will call calculateValue, return its result, and store it in case it can be reused later.

  • dependencies: The list of all reactive values referenced inside of the calculateValue code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison algorithm.

On the initial render, useMemo returns the result of calling calculateValue with no arguments.During subsequent renders, it will either return an already stored value from the last render (if the dependencies haven’t changed), or call calculateValue again, and return the result that calculateValue has returned.

Caveats

  • useMemo is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
  • In Strict Mode, React will call your calculation function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your calculation function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
  • React will not throw away the cached value unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on useMemo solely as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.

Usage

By default, React will re-run the entire body of your component every time that it re-renders. For example, if this TodoList updates its state or receives new props from its parent, the filterTodos function will re-run:

import { useMemo } from 'react';

function TodoList({ todos, tab }) {
  const visibleTodos = useMemo(
    () => filterTodos(todos, tab),
    [todos, tab]
  );
  // ...
}

What is the use of useCallback Hooks in reactjs?

useCallback is a React Hook that lets you cache a function definition between re-renders.

const cachedFn = useCallback(fn, dependencies)

usecallback takes two parameters, the first one is function which you wants to cache and second one is dependencies.

  • fn: The function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On subsequent renders, React will give you the same function again if the dependencies have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it.

  • dependencies: The list of all reactive values referenced inside of the fn code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison algorithm.

useCallback returns the fn function you have passed.During subsequent renders, it will either return an already stored function from the last render (if the dependencies haven’t changed), or return the fn function you have passed during this render.

Caveats

  • useCallback is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.

  • React will not throw away the cached function unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component.

  • Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on useCallback as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.

Usage

Say you’re passing a handleSubmit function down from the ProductPage to the ShippingForm component:

In this example, the ShippingForm component is artificially slowed down so that you can see what happens when a React component you’re rendering is genuinely slow. Try incrementing the counter and toggling the theme.

Incrementing the counter feels slow because it forces the slowed down ShippingForm to re-render. That’s expected because the counter has changed, and so you need to reflect the user’s new choice on the screen.

Next, try toggling the theme. Thanks to useCallback together with memo, it’s fast despite the artificial slowdown! ShippingForm skipped re-rendering because the handleSubmit function has not changed. The handleSubmit function has not changed because both productId and referral (your useCallback dependencies) haven’t changed since last render.

//App.js
import { useState } from 'react';
import ProductPage from './ProductPage.js';
export default function App() {
  const [isDark, setIsDark] = useState(false);
  return (
    <>
      <label>
        <input
          type="checkbox"
          checked={isDark}
          onChange={e => setIsDark(e.target.checked)}
        />
        Dark mode
      </label>
      <hr />
      <ProductPage
        referrerId="wizard_of_oz"
        productId={123}
        theme={isDark ? 'dark' : 'light'}
      />
    </>
  );
}
//ProductPage.js
import { useCallback } from 'react';
import ShippingForm from './ShippingForm.js';
export default function ProductPage({ productId, referrer, theme }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails,
    });
  }, [productId, referrer]);
  return (
    <div className={theme}>
      <ShippingForm onSubmit={handleSubmit} />
    </div>
  );
import { memo, useState } from 'react';
const ShippingForm = memo(function ShippingForm({ onSubmit }) {
  const [count, setCount] = useState(1);
  console.log('[ARTIFICIALLY SLOW] Rendering <ShippingForm />');
  let startTime = performance.now();
  while (performance.now() - startTime < 500) {
    // Do nothing for 500 ms to emulate extremely slow code
  }
  function handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    const orderDetails = {
      ...Object.fromEntries(formData),
      count
    };
    onSubmit(orderDetails);
  }
  return (
    <form onSubmit={handleSubmit}>
      <p><b>Note: <code>ShippingForm</code> is artificially slowed down!</b></p>
      <label>
        Number of items:
        <button type="button" onClick={() => setCount(count - 1)}>–</button>
        {count}
        <button type="button" onClick={() => setCount(count + 1)}>+</button>
      </label>
      <label>
        Street:
        <input name="street" />
      </label>
      <label>
        City:
        <input name="city" />
      </label>
      <label>
        Postal code:
        <input name="zipCode" />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
});

export default ShippingForm;

How to make custom Hooks in reactjs?

React comes with several built-in Hooks like useState, useContext, and useEffect. Sometimes, you’ll wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. You might not find these Hooks in React, but you can create your own Hooks for your application’s needs.


import { useState, useEffect } from 'react';

export function useOnlineStatus() {
  const [isOnline, setIsOnline] = useState(true);
  useEffect(() => {
    function handleOnline() {
      setIsOnline(true);
    }
    function handleOffline() {
      setIsOnline(false);
    }
    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);
    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);
  return isOnline;
}

What is Higher Order Components?

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

When do we need a Higher Order Component?

While developing React applications, we might develop components that are quite similar to each other with minute differences. In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY, 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.

Example of a HOC:

// HOC.js

import React, {Component} from 'react';

export default function Hoc(HocComponent){
    return function Component(){
        render(){
            return (
                <div>
                    <HocComponent></HocComponent>
                </div>

            );
        }
    } 
}
import React, { Component } from 'react';
import Hoc from './HOC';

function App() {
  
    return (
      <div>
        Higher-Order Component
      </div>
    )
}
const App = Hoc(App);
export default App;