Top ReactJS Questions

Q (1): What is React.js?

React is a JavaScript library created for building fast and interactive user interfaces for web and mobile applications. It is an open-source, component-based, front-end library responsible only for the application view layer.

The main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. It uses virtual DOM (JavaScript object), which improves the performance of the app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on the client and server-side as well as with other frameworks. It uses component and data patterns that improve readability and helps to maintain larger apps.

Read More


Q (2): How React works?

While building client-side apps, a team at Facebook developers realized that the DOM is slow (The Document Object Model (DOM) is an application programming interface (API) for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated). So, to make it faster, React implements a virtual DOM that is basically a DOM tree representation in Javascript. So when it needs to read or write to the DOM, it will use the virtual representation of it. Then the virtual DOM will try to find the most efficient way to update the browsers DOM.

Unlike browser DOM elements, React elements are plain objects and are cheap to create. React DOM takes care of updating the DOM to match the React elements. The reason for this is that JavaScript is very fast and it is worth keeping a DOM tree in it to speedup its manipulation.


Q (3): What are Components in React?

<img src="assets/component-tree.png" alt="Components Tree" width="600px" />

Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

A react application is made of multiple components, each responsible for rendering a small, reusable piece of HTML. Components can be nested within other components to allow complex applications to be built out of simple building blocks. A component may also maintain internal state – for example, a TabList component may store a variable corresponding to the currently open tab.

Example: Class Component

class Welcome extends React.Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}


Q (4): List some of the major advantages and limitations of React?

<img src="assets/react-features.png" alt="React-Features" width="500px" />

Advantages

  • It relies on a virtual-dom to know what is really changing in UI and will re-render only what has really changed, hence better performance wise
  • JSX makes components/blocks code readable. It displays how components are plugged or combined with.
  • React data binding establishes conditions for creation dynamic applications.
  • Prompt rendering. Using comprises methods to minimise number of DOM operations helps to optimise updating process and accelerate it. Testable. React native tools are offered for testing, debugging code.
  • SEO-friendly. React presents the first-load experience by server side rendering and connecting event-handlers on the side of the user:
    • React.renderComponentToString is called on the server.
    • React.renderComponent() is called on the client side.
    • React preserves markup rendered on the server side, attaches event handlers.

Limitations

  • Learning curve. Being not full-featured framework it is requered in-depth knowledge for integration user interface free library into MVC framework.
  • View-orientedness is one of the cons of ReactJS. It should be found 'Model' and 'Controller' to resolve 'View' problem.
  • Not using isomorphic approach to exploit application leads to search engines indexing problems.


Q (5): What is JSX and how JSX can help applications in React.js?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() or appendChild() methods. JSX converts HTML tags into react elements. React uses JSX for templating instead of regular JavaScript. It is not necessary to use it, however, following are some pros that come with it.

  • It is faster because it performs optimization while compiling code to JavaScript.
  • It is also type-safe and most of the errors can be caught during compilation.
  • It makes it easier and faster to write templates.

Example:

import React from 'react';

class App extends React.Component {

   render() {
      return (
         <div>
            Hello World!
         </div>
      );
   }
}
export default App;

JSX is a JavaScript Expression

JSX expressions are JavaScript expressions too. When compiled, they actually become regular JavaScript objects. For instance, the code below:

const hello = <h1 className = "greet"> Hello World </h1>

will be compiled to

const hello = React.createElement {
    type: "h1",
    props: {
      className: "greet",  
      children: "Hello World"
    }
}

Since they are compiled to objects, JSX can be used wherever a regular JavaScript expression can be used.


Q (6): What is ReactDOM?

ReactDOM() is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page. ReactDOM provides the developers with an API containing following methods and a few more.

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

React DOM is the glue between React and the DOM. When u want to show your react component on DOM u need to use this ReactDOM.render(); from React Dom.

Before v0.14 React Dom was part of React. The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps. ReactDOM uses observables thus provides an efficient way of DOM handling. ReactDOM can be used in both client-side and server-side.

Example:

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App/App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

To use the ReactDOM in any React web app we must first import ReactDOM from the react-dom package by using the following code snippet:

import ReactDOM from 'react-dom'

a.) ReactDOM.render() Function

This function is used to render a single React Component or several Components wrapped together in a Component or a div element. This function uses the efficient methods of React for updating the DOM by being able to change only a subtree, efficient diff methods etc. This function returns a reference to the component or null if a stateless component was rendered.

ReactDOM.render() replaces the child of the given container if any. It uses highly efficient diff algorithm and can modify any subtree of the DOM.

ReactDOM.render(element, container, callback)
  • element: This parameter expects a JSX expression or a React Element to be rendered.
  • container: This parameter expects the container in which the element has to be rendered.
  • callback: This is an optional parameter that expects a function that is to be executed once the render is complete.

b.) findDOMNode() Function

This function is generally used to get the DOM node where a particular React component was rendered. This method is very less used as the following can be done adding a ref attribute to each component itself.

findDOMNode() function can only be implemented upon mounted components thus Functional components can not be used in findDOMNode() method.

ReactDOM.findDOMNode(component)

This method takes a single parameter component which expects a React Component to be searched in the Browser DOM. This function returns the DOM node where the component was rendered on success otherwise null.

c.) unmountComponentAtNode() Function

This function is used to unmount or remove the React Component that was rendered to a particular container.

ReactDOM.unmountComponentAtNode(container)

This method takes a single parameter container which expects the DOM container from which the React component has to be removed. This function returns true on success otherwise false.

d.) hydrate() Function

This method is equivalent to the render() method but is implemented while using server-side rendering.

ReactDOM.hydrate(element, container, callback)
  • element: This parameter expects a JSX expression or a React Component to be rendered.
  • container: This parameter expects the container in which the element has to be rendered.
  • callback: This is an optional parameter that expects a function that is to be executed once the render is complete.

This function attempts to attach event listeners to the existing markup and returns a reference to the component or null if a stateless component was rendered.

e.) createPortal() Function

Usually, when an element is returned from a component's render method, it's mounted on the DOM as a child of the nearest parent node which in some cases may not be desired. Portals allow us to render a component into a DOM node that resides outside the current DOM hierarchy of the parent component.

ReactDOM.createPortal(child, container)
  • child: This parameter expects a JSX expression or a React Component to be rendered.
  • container: This parameter expects the container in which the element has to be rendered.


Q (7): What is the difference between ReactDOM and React?

import React from 'react'; /* importing react */
import ReactDOM from 'react-dom'; /* importing react-dom */

class MyComponent extends React.Component {

  render() {
    return <div>Hello World</div>;
  }
});

ReactDOM.render(<MyComponent />, node);

React package contains: React.createElement(), React.createClass(), React.Component(), React.PropTypes(), React.Children()

ReactDOM package contains: ReactDOM.render(), ReactDOM.unmountComponentAtNode(), ReactDOM.findDOMNode(), and react-dom/server that including: ReactDOMServer.renderToString() and ReactDOMServer.renderToStaticMarkup().

The ReactDOM module exposes DOM-specific methods, while React has the core tools intended to be shared by React on different platforms (e.g. React Native).


Q (8): What are the differences between a class component and functional component?

Functional Components

  • Functional components are basic JavaScript functions. These are typically arrow functions but can also be created with the regular function keyword.
  • Sometimes referred to as stateless components as they simply accept data and display them in some form; that is they are mainly responsible for rendering UI.
  • React lifecycle methods (for example, componentDidMount()) cannot be used in functional components.
  • There is no render method used in functional components.
  • These are mainly responsible for UI and are typically presentational only (For example, a Button component).
  • Functional components can accept and use props.
  • Functional components should be favored if you do not need to make use of React state.

Example:

const ClockUsingHooks = props => {
    const [time, setTime] = useState(new Date())

    const changeTime = () => {
        setTime(new Date())
    }

    useEffect(() => {
        const tick = setInterval(() => {
            changeTime()
        }, 1000)
        return () => clearInterval(tick)
    })
    return (
        <div className="clock">
            <h1>Hello! This is a function component clock.</h1>
            <h2>It is {time.toLocaleTimeString()}.</h2>
        </div>
    )
}

export default ClockUsingHooks

Class Components

  • Class components make use of ES6 class and extend the Component class in React.
  • Sometimes called stateful components as they tend to implement logic and state.
  • React lifecycle methods can be used inside class components (for example, componentDidMount()).
  • We pass props down to class components and access them with this.props.
  • Class-based components can have refs to underlying DOM nodes.
  • Class-based components can use shouldComponentUpdate() and PureComponent() performance optimisation techniques.

Example:

class ClockUsingClass extends React.Component {
    constructor(props) {
        super(props)
        this.state = { date: new Date() }
    }

    componentDidMount() {
        this.time = setInterval(() => {
            this.changeTime()
        }, 1000)
    }

    componentWillUnmount() {
        clearInterval(this.time)
    }

    changeTime() {
        this.setState({ date: new Date() })
    }

    render() {
        return (
            <div className="clock">
                <h1>Hello! This is a class component clock.</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
            </div>
        )
    }
}

export default ClockUsingClass


Q (9): What is the difference between state and props?

State

This is data maintained inside a component. It is local or owned by that specific component. The component itself will update the state using the setState() function.

Example:

class Employee extends React.Component {
    constructor() {
        this.state = {
            id: 1,
            name: "Alex"
        };  
    }

    render() {
        return (
            <div>
              <p>{this.state.id}</p>
              <p>{this.state.name}</p>
            </div>
        );  
    }
}

export default Employee

Props

Data passed in from a parent component. props are read-only in the child component that receives them. However, callback functions can also be passed, which can be executed inside the child to initiate an update.

Example:

class ParentComponent extends Component {
    render() {
        return (
            <ChildComponent name="First Child" />
        );  
    }
}

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

Difference between State and Props

Props State
Props are read-only. State changes can be asynchronous.
Props are immutable. State is mutable.
Props allow you to pass data from one component to other components as an argument. State holds information about the components.
Props can be accessed by the child component. State cannot be accessed by child components.
Props are used to communicate between components. States can be used for rendering dynamic changes with the component.
Stateless component can have Props. Stateless components cannot have State.
Props make components reusable. State cannot make components reusable.
Props are external and controlled by whatever renders the component. The State is internal and controlled by the React Component itself.


Q (10): How would you create Higher Order Components (HOCs) in React.js?

<img src="assets/Higher-Order-Components.jpg" alt="Higher Order Components" width="500px" />

A higher-order component is a function that takes a component and returns a new component. A higher-order component (HOC) is the advanced technique in React.js for reusing a component logic. Higher-Order Components are not part of the React API. They are the pattern that emerges from React's compositional nature. The component transforms props into UI, and a higher-order component converts a component into another component. The examples of HOCs are Redux's connect and Relay's createContainer.

// HOC.js

import React, {Component} from 'react';

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

            );
        }
    }
}
// App.js

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

class App extends Component {
  
  render() {
    return (
      <div>
        Higher-Order Component Example!
      </div>
    )
  }
}
App = Hoc(App);
export default App;

Notes

  • We do not modify or mutate components. We create new ones.
  • A HOC is used to compose components for code reuse.
  • A HOC is a pure function. It has no side effects, returning only a new component.