React is an efficient, flexible, and open-source JavaScript framework library that allows developers to the creation of simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook has created React. It was first deployed on the news feed of Facebook in 2011 and on Instagram in 2012. Developers from the Javascript background can easily develop web applications with the help of React.
React Hooks will allow you to use the state and other features of React in which requires a class to be written by you. In simple words, we can say that, React Hooks are the functions that will connect React state with the lifecycle features from the function components. React Hooks is among the features that are implemented latest in the version React 16.8.
The selection of the right technology for the application or web development is becoming more challenging. React has been considered to be the fastest-growing Javascript framework among all. The tools of Javascript are firming their roots slowly and steadily in the marketplace and the React certification demand is exponentially increasing. React is a clear win for front-end developers as it has a quick learning curve, clean abstraction, and reusable components. Currently, there is no end in sight for React as it keeps evolving.
React is a front-end and open-source JavaScript library which is useful in developing user interfaces specifically for applications with a single page. It is helpful in building complex and reusable user interface(UI) components of mobile and web applications as it follows the component-based approach.
The important features of React are:
The few limitations of React are as given below:
React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components. These are newly added features made available in React 16.8 version. 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.
The useState() is a built-in React Hook that allows you for having state variables in functional components. It should be used when the DOM has something that is dynamically manipulating/controlling.
In the below-given example code, The useState(0) will return a tuple where the count is the first parameter that represents the counter's current state and the second parameter setCounter method will allow us to update the state of the counter.
...
const [count, setCounter] = useState(0);
const [otherStuffs, setOtherStuffs] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setOtherStuffs(...);
...
};
We can make use of setCounter() method for updating the state of count anywhere. In this example, we are using setCounter() inside the setCount function where various other things can also be done. The idea with the usage of hooks is that we will be able to keep our code more functional and avoid class-based components if they are not required.
There are 2 rules which must be followed while you code with Hooks:
The useEffect React Hook is used for performing the side effects in functional components. With the help of useEffect, you will inform React that your component requires something to be done after rendering the component or after a state change. The function you have passed(can be referred to as “effect”) will be remembered by React and call afterward the performance of DOM updates is over. Using this, we can perform various calculations such as data fetching, setting up document title, manipulating DOM directly, etc, that don't target the output value. The useEffect hook will run by default after the first render and also after each update of the component. React will guarantee that the DOM will be updated by the time when the effect has run by it.
The useEffect React Hook will accept 2 arguments:
useEffect(callback[, dependencies]);
Where the first argument callback represents the function having the logic of side-effect and it will be immediately executed after changes were being pushed to DOM. The second argument dependencies represent an optional array of dependencies. The useEffect() will execute the callback only if there is a change in dependencies in between renderings.
Example:
import { useEffect } from 'react';
function WelcomeGreetings({ name }) {
const msg = `Hi, ${name}!`; // Calculates output
useEffect(() => {
document.title = `Welcome to you ${name}`; // Side-effect!
}, [name]);
return <div>{msg}</div>; // Calculates output
}
The above code will update the document title which is considered to be a side-effect as it will not calculate the component output directly. That is why updating of document title has been placed in a callback and provided to useEffect().
Consider you don't want to execute document title update each time on rendering of WelcomeGreetings component and you want it to be executed only when the name prop changes then you need to supply name as a dependency to useEffect(callback, [name])
.
Earlier, refs were only limited to class components but now it can also be accessible in function components through the useRef Hook in React.
The refs are used for:
A Custom Hook is a function in Javascript whose name begins with ‘use’ and which calls other hooks. It is a part of React v16.8 hook update and permits you for reusing the stateful logic without any need for component hierarchy restructuring.
In almost all of the cases, custom hooks are considered to be sufficient for replacing render props and HoCs (Higher-Order components) and reducing the amount of nesting required. Custom Hooks will allow you for avoiding multiple layers of abstraction or wrapper hell that might come along with Render Props and HoCs.
The disadvantage of Custom Hooks is it cannot be used inside of the classes.
There are two types of side effects in React component. They are:
The props in React are the inputs to a component of React. They can be single-valued or objects having a set of values that will be passed to components of React during creation by using a naming convention that almost looks similar to HTML-tag attributes. We can say that props are the data passed from a parent component into a child component.
The main purpose of props is to provide different component functionalities such as:
this.props.reactProp
inside render() method of component.For example, consider we are creating an element with reactProp property as given below:
<Element reactProp = "1" />
This reactProp name will be considered as a property attached to native props object of React which already exists on each component created with the help of React library.
props.reactProp;
There are four different phases in the lifecycle of React component. They are:
componentWillMount
and componentDidMount
.componentWillUpdate
, shouldComponentUpdate
, render
, and componentDidUpdate
.componentWillUnmount
.React lifecycle hooks will have the methods that will be automatically called at different phases in the component lifecycle and thus it provides good control over what happens at the invoked point. It provides the power to effectively control and manipulate what goes on throughout the component lifecycle.
For example, if you are developing the YouTube application, then the application will make use of a network for buffering the videos and it consumes the power of the battery (assume only these two). After playing the video if the user switches to any other application, then you should make sure that the resources like network and battery are being used most efficiently. You can stop or pause the video buffering which in turn stops the battery and network usage when the user switches to another application after video play.
So we can say that the developer will be able to produce a quality application with the help of lifecycle methods and it also helps developers to make sure to plan what and how to do it at different points of birth, growth, or death of user interfaces.
The various lifecycle methods are:
constructor()
: This method will be called when the component is initiated before anything has been done. It helps to set up the initial state and initial values.getDerivedStateFromProps()
: This method will be called just before element(s) rendering in the DOM. It helps to set up the state object depending on the initial props. The getDerivedStateFromProps() method will have a state as an argument and it returns an object that made changes to the state. This will be the first method to be called on an updating of a component.render()
: This method will output or re-render the HTML to the DOM with new changes. The render() method is an essential method and will be called always while the remaining methods are optional and will be called only if they are defined.componentDidMount()
: This method will be called after the rendering of the component. Using this method, you can run statements that need the component to be already kept in the DOM.shouldComponentUpdate()
: The Boolean value will be returned by this method which will specify whether React should proceed further with the rendering or not. The default value for this method will be True.getSnapshotBeforeUpdate()
: This method will provide access for the props as well as for the state before the update. It is possible to check the previously present value before the update, even after the update.componentDidUpdate()
: This method will be called after the component has been updated in the DOM.componentWillUnmount()
: This method will be called when the component removal from the DOM is about to happen.Static typing refers to the process of code check during the time of compilation for ensuring all variables will be statically typed. React Hooks are functions that are designed to make sure about all attributes must be statically typed. For enforcing stricter static typing within our code, we can make use of the React API with custom Hooks.
There are two types of Hooks in React. They are:
useState()
: This functional component is used to set and retrieve the state.useEffect()
: It enables for performing the side effects in the functional components.useContext()
: It is used for creating common data that is to be accessed by the components hierarchy without having to pass the props down to each level.useReducer()
: It is used when there is a complex state logic that is having several sub-values or when the upcoming state is dependent on the previous state. It will also enable you to optimization of component performance that will trigger deeper updates as it is permitted to pass the dispatch down instead of callbacks.useMemo()
: This will be used for recomputing the memoized value when there is a change in one of the dependencies. This optimization will help for avoiding expensive calculations on each render.useCallback()
: This is useful while passing callbacks into the optimized child components and depends on the equality of reference for the prevention of unneeded renders.useImperativeHandle()
: It will enable modifying the instance that will be passed with the ref object.useDebugValue()
: It is used for displaying a label for custom hooks in React DevTools.useRef()
: It will permit creating a reference to the DOM element directly within the functional component.useLayoutEffect()
: It is used for reading layout from the DOM and re-rendering synchronously.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 |
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.
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:
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.
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:
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 npmjs.com 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 a app initializer created by Facebook, to help with 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 favorite 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.js
and putting the following code into it.
import React from 'react';
export function SearchItem() {
return (
<div>
<div className="search-input">
<input type="text" placeholder="SearchItem"/>
</div>
<h1 className="h1">Search Results</h1>
<div className="items">
<table>
<thead>
<tr>
<th className="itemname-col">Item Name</th>
<th className="price-col">Price</th>
<th className="quantity-col">Quantity</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
);
}
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="App">
<header>
Items with Hooks
</header>
<SearchItem/>
</div>
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.
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[props.page] || 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
}
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 WindowSizeDimensions extends React.Component {
constructor(props){
super(props);
this.updateDimension = this.updateDimension.bind(this);
}
componentWillMount() {
this.updateDimension()
}
componentDidMount() {
window.addEventListener('resize', this.updateDimension)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimension)
}
updateDimension() {
this.setState({width: window.innerWidth, height: window.innerHeight})
}
render() {
return <span>{this.state.width} x {this.state.height}</span>
}
}
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 AppDemo extends Component {
render() {
return (
<Router>
<div className="AppDemo">
<ul>
<li>
<NavLink to="/" activeStyle={{ color:'blue' }}>Home</NavLink>
</li>
<li>
<NavLink to="/about" activeStyle={{ color:'blue' }}>About
</NavLink>
</li>
</ul>
<Route path="/about/:aboutId" component={AboutPage} />
<Route path="/about" component={AboutPage} />
<Route path="/" component={HomePage} />
</div>
</Router>
);
}
}
export default AppDemo;
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 HomePage(props) {
const handleClick = (data) => {
props.history.push('/about/' + data);
}
return (
<div>
<button onClick={() => handleClick('DemoButton')}>To About</button>
</div>
)
}
Also, the functional component AboutPage will obtain the data passed by props.match.params.aboutId
.
export default function AboutPage(props) {
if(!props.match.params.aboutId) {
return <div>No Data Yet</div>
}
return (
<div>
{`Data obtained from HomePage is ${props.match.params.aboutId}`}
</div>
)
}
After button click in the HomePage the page will look like below:
The react-router package will provide the component <Redirect>
in React Router. Rendering of a <Redirect>
component will navigate to a newer location. In the history stack, the current location will be overridden by the new location just like the server-side redirects.
import React, { Component } from 'react'
import { Redirect } from 'react-router'
export default class LoginDemoComponent extends Component {
render() {
if (this.state.isLoggedIn === true) {
return <Redirect to="/your/redirect/page" />
} else {
return <div>{'Please complete login'}</div>
}
}
}
React has got more popularity among the top IT companies like Facebook, PayPal, Instagram, Uber, etc., around the world especially in India. Hooks is becoming a trend in the React community as it removes the state management complexities.
This article includes the most frequently asked ReactJS and React Hooks interview questions and answers that will help you in interview preparations. Also, remember that your success during the interview is not all about your technical skills, it will also be based on your state of mind and the good impression that you will make at first. All the best!!
npm install create-react-app
install -g create-react-app
npm install -g create-react-app
npm install -g create-react-app