react js interview questions

What is React?

React(aka React.js or ReactJS) is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.

React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 2011 and on Instagram in 2012.

What are the major features of React?

The major features of React are:

  • Uses JSX syntax, a syntax extension of JS that allows developers to write HTML in their JS code.

  • It uses Virtual DOM instead of Real DOM considering that Real DOM manipulations are expensive.

  • Supports server-side rendering which is useful for Search Engine Optimizations(SEO).

  • Follows Unidirectional or one-way data flow or data binding.

  • Uses reusable/composable UI components to develop the view.

What is JSX?

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

    In the example below, the text inside <h1> tag is returned as JavaScript function to the render function.

     export default function App() {
       return (
           <h1 className="greeting">{"Hello, this is a JSX Code!"}</h1>
       );
     }
    

    If you don't use JSX syntax then the respective JavaScript code should be written as below,

     import { createElement } from 'react';
    
     export default function App() {
       return createElement(
         'h1',
         { className: 'greeting' },
         'Hello, this is a JSX Code!'
       );
     }
    
    See Class

    Note: JSX is stricter than HTML

what is pure component

ChatGPT

In React, a pure component is a type of component that is designed to optimize rendering performance by preventing unnecessary re-renders. Pure components are a subclass of the standard React.Component class, and they automatically implement the shouldComponentUpdate lifecycle method with a shallow comparison of props and state.

How Pure Components Work: When a component updates, React checks whether the new props or state are different from the previous ones. By default, React will re-render the component even if the new props or state are the same as the previous ones, potentially causing unnecessary re-renders and impacting performance.

Pure components, on the other hand, perform a shallow comparison of the props and state between renders. If the props and state are the same as the previous ones, the pure component will not re-render, effectively skipping the rendering process and improving performance.

Creating a Pure Component: In order to create a pure component in React, you can extend the React.PureComponent class instead of the standard React.Component class.

jsxCopy codeimport React from 'react';

class MyPureComponent extends React.PureComponent {
  render() {
    // Component's render logic
    return (
      // JSX representing the component's UI
    );
  }
}

When to Use Pure Components: Pure components are beneficial when you have components that receive a lot of props, and the rendering process is resource-intensive. By using pure components, you can reduce the number of unnecessary re-renders, leading to better performance and a smoother user experience.

It's important to note that using pure components is not always necessary or appropriate. They should be used judiciously, mainly in situations where you have performance bottlenecks due to frequent re-renders caused by receiving the same props or state.

Limitations of Pure Components: While pure components are powerful tools for optimizing performance, they have some limitations:

  1. Shallow Comparison: Pure components perform a shallow comparison of props and state. If your component's props or state contain complex data structures (e.g., nested objects or arrays), shallow comparison might not be sufficient to determine if the data has changed. In such cases, you might need to consider other optimization techniques or use libraries like immutable.js or immer to handle deep data structures.

  2. Function Props: Pure components might not work optimally when receiving function props that change with each render, as the shallow comparison would detect the functions as different, even if their content remains the same. In such cases, you might need to use useCallback (in functional components) or other techniques to memoize the function props and avoid unnecessary re-renders.

  3. Not Supported in Functional Components: While functional components can use the React.memo Higher-Order Component (HOC) for similar performance optimization, they don't have the concept of pure components like class components do.

In summary, pure components are a valuable tool for optimizing React application performance by reducing unnecessary re-renders. However, they should be used thoughtfully in conjunction with other performance optimization techniques to create efficient and responsive React applications.

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. The important point is whenever the state object changes, the component re-renders. It is always recommended to make our state as simple as possible and minimize the number of stateful components.

state

Let's take an example of User component with message state. Here, useState hook has been used to add state to the User component and it returns an array with current state and function to update it.

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 similar to HTML-tag attributes. Here, the data is passed down from a parent component to a child component.

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

    1. Pass custom data to your component.

    2. Trigger state changes.

    3. 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) attribute 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

For example, the usage of props in function component looks like below:

    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>
      );
    };

The properties from props object can be accessed directly using destructing feature from ES6 (ECMAScript 2015). The above child component can be simplified like below.

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

What is the difference between state and props?

In React, both state and props are plain JavaScript objects and used to manage the data of a component, but they are used in different ways and have different characteristics. state is managed by the component itself and can be updated using the setState() function. Unlike props, state can be modified by the component and is used to manage the internal state of the component. Changes in the state trigger a re-render of the component and its children. props (short for "properties") are passed to a component by its parent component and are read-only, meaning that they cannot be modified by the component itself. props can be used to configure the behavior of a component and to pass data between components.

Why should we not update the state directly?

If you try to update the state directly then it won't re-render the component.

//Wrong
this.state.message = "Hello world";

Instead use setState() method. It schedules an update to a component's state object. When state changes, the component responds by re-rendering.

//Correct
this.setState({ message: "Hello World" });

Note: You can directly assign to the state object either in constructor or using latest javascript's class field declaration syntax.

What is the difference between HTML and React event handling?

Below are some of the main differences between HTML and React event handling,

  1. In HTML, the event name usually represents in lowercase as a convention:

     <button onclick="activateLasers()"></button>
    

    Whereas in React it follows camelCase convention:

     <button onClick={activateLasers}>
    
  2. In HTML, you can return false to prevent default behavior:

     <a
       href="#"
       onclick='console.log("The link was clicked."); return false;'
     />
    

    Whereas in React you must call preventDefault() explicitly:

     function handleClick(event) {
       event.preventDefault();
       console.log("The link was clicked.");
     }
    
  3. In HTML, you need to invoke the function by appending () Whereas in react you should not append () with the function name. (refer "activateLasers" function in the first point for example)