Question-31. Differentiate React Hooks vs Classes.

React Hooks Classes
It is used in functional components of React. It is used in class-based components of React.
It will not require a declaration of any kind of constructor. It is necessary to declare the constructor inside the class component.
It does not require the use of this keyword in state declaration or modification. Keyword this will be used in state declaration (this.state) and in modification (this.setState()).
It is easier to use because of the useState functionality. No specific function is available for helping us to access the state and its corresponding setState variable.
React Hooks can be helpful in implementing Redux and context API. Because of the long setup of state declarations, class states are generally not preferred.

Question-32. How does the performance of using Hooks will 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 since they will be avoiding the nesting that exists in HOCs (Higher Order Components) and will render props which result in less amount of work to be done by React.

Question-33. Do Hooks cover all the functionalities provided by the classes?

Answer- Our goal is 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, few third-party libraries may not be compatible with Hooks at present, but they will be added soon.

Question-34. What is React Router?

Answer- React Router refers to the standard library used for routing in React. It permits us for building a single-page web application in React with navigation without even refreshing the page when the user navigates. It also allows to change the browser URL and will keep the user interface in sync with the URL. React Router will make use of the component structure for calling the components, using which appropriate information can be shown. Since React is a component-based framework, it’s not necessary to include and use this package. 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 make use of the HTML5 history API (pushState, popstate, and event replaceState) for keeping your UI to be in sync with the URL. It is the parent component useful in storing all other components.
  • Routes: It is a newer component that has been introduced in the React v6 and an upgrade of the component.
  • Route: It is considered to be 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 all over the application. It works similarly to the anchor tag in HTML.

Question-35. Can React Hook replaces Redux?

Answer- The React Hook cannot be considered as 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 useReducer 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 which are dependent on each other, instead of a declaration of multiple useState hooks.In commercial web applications which is larger, the complexity will be high, so using only React Hook may not be sufficient. Few developers will try to tackle the challenge with the help of React Hooks and others will combine React Hooks with the Redux.

Question-36. Explain conditional rendering in React.

Answer- 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 for medium-sized applications
  • Using ternary operators, which takes away some amount of complication from if-else statements
  • Using element variables, which will enable us to write cleaner code.

Question-37. Explain how to create a simple React Hooks example program.

Answer- I will assume that you are having some coding knowledge about JavaScript and have installed Node on your system for creating a below given React Hook program. An installation of Node comes along 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 commands of Node from the command line. The npx looks in the current project folder for checking whether a command has been installed there. When the command is not available on your computer, the npx will look in the repository, then the latest version of the command script will be loaded and will run without locally installing it. This feature is useful in creating a skeleton React application within a few key presses.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 quick creation of React application, providing options to customize it while creating the application? The above command will create a new folder named react-items-with-hooks and it will be initialized with a basic React application. Now, you will be able to 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 is having a single function App() which will return an element and it will make use of an extended JavaScript syntax(JSX) for defining the component.

JSX will permit you for writing HTML-style template syntax directly into the JavaScript file. This mixture of JavaScript and HTML will be converted by React toolchain into pure JavaScript that will render the HTML element.

It is possible to define your own React components by writing a function that will return a JSX element. You can try this by creating a new file src/SearchItem.jsand put the following code into it.

import React from 'react';
export Myfunction SearchItem() {
 return (
     <div className="search-input">
       <input type="text" placeholder="SearchItem"/>
     <h1 className="h1">Search Results</h1>
     <div className="items">
             <th className="itemname-col">Item Name</th>
             <th className="price-col">Price</th>
             <th className="quantity-col">Quantity</th>

This is all about how you can create a component. It will only display the empty table and doesn’t do anything. But you will be able to use the Search component in the application. 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, import will be removed and then contents of returned value in the function App() will be replaced with the following code:

<div className="MyApp">
   Items with Hooks

You can notice that the element <SearchItem/> has been used just similar to an HTML element. The JSX syntax will enable for including the components in this approach directly within the JavaScript code. Your application can be tested by running the below-given command in your terminal.

npm start

This command will compile your application and open your default browser into http://localhost:4000. This command can be kept on running when code development is in progress to make sure that the application is up-to-date, and also this browser page will be reloaded each time you modify and save the code.

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

Question-38. How to create a switching component for displaying different pages?

Answer- A switching component refers to a component that will render one of the multiple components. We should use an object for mapping prop values to components.A below-given example will show you how to display different pages based on page prop using switching component:

import HomePage from './HomePage'
import AboutPage from './AboutPage'
import FacilitiesPage from './FacilitiesPage'
import ContactPage from './ContactPage'
import HelpPage from './HelpPage'
const PAGES = {
 home: HomePage,
 about: AboutPage,
 facilitiess: FacilitiesPage,
 contact: ContactPage
 help: HelpPage
const Page = (props) => {
 const Handler = PAGES[] || HelpPage
 return <Handler {...props} />
// The PAGES object keys can be used in the prop types for catching errors during dev-time.
Page.propTypes = {
 page: PropTypes.oneOf(Object.keys(PAGES)).isRequired

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

Answer- It is possible to listen to the resize event in componentDidMount() and then update the width and height dimensions. It requires the removal of the event listener in the componentWillUnmount() method.Using the below-given code, we can render the view when the browser is resized.

class MyWindowSizeDimensions extends React.Component {
   this.updateDimension = this.updateDimension.bind(this);
 componentWillMount() {
 componentDidMount() {
   Mywindow.addEventListener('resize', this.updateDimension)
 componentWillUnmount() {
   Mywindow.removeEventListener('resize', this.updateDimension)
 updateDimension() {
   this.setState({width: Mywindow.innerWidth, height: Mywindow.innerHeight})
 render() {
   return <span>{this.state.width} x {this.state.height}</span>

Question-40. How to pass data between sibling components using React router?

Answer- Passing data between sibling components of React is possible using React Router with the help of history.push and match.params.In the code given below, we have a Parent component AppDemo.js and have two Child Components HomePage and AboutPage. Everything is kept inside a Router by using React-router Route. It is also having a route for /about/{params} where we will pass the data.

import React, { Component } from ‘react’;
class MyAppDemo extends Component {
render() {
  return (
      <div className="MyAppDemo">
          <NavLink to="/"  activeStyle={{ color:'blue' }}>Home</NavLink>
          <NavLink to="/about"  activeStyle={{ color:'blue' }}>About
             <Route path="/about/:aboutId" component={AboutPage} />
             <Route path="/about" component={AboutPage} />
             <Route path="/" component={HomePage} />
export default MyAppDemo;

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

export default function MyHomePage(props) {
 const handleClick = (data) => {
  props.history.push('/about/' + data);
return (
    <button onClick={() => handleClick('DemoButton')}>To About</button>

Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId.

export default function MyAboutPage(props) {
if(!props.match.params.aboutId) {
    return <div>No Data Yet</div>
return (
    {`Data obtained from HomePage is ${props.match.params.aboutId}`}