Search

Introduction to Hooks in React

Technological change is rapidly impacting our present and our prospects for the future, and so are frontend frameworks, which are emerging at a very fast pace these days. And in many ways, React, the most popular framework amongst the JavaScript community, is turning out to be unstoppable.   Many of us have already played around with Hooks or have at least heard about them. But there are still many who are probably yet to take the time or have had the chance to experiment with them.  No worries, sooner or later you will find yourself diving into Hooks.  In this article, you will learn about the term, ‘Hooks’, and the reasons why you should use them in your future projects. Furthermore, you will learn about how you can use React Hooks in the best possible manner to build some awesome features in your projects and write cleaner code.  What exactly is a Hook? Hooks are just regular JavaScript functions. In layman terms, hooks provide a way to use functionalities such as context or state, which could earlier only be achieved through classes, and now can easily be done using function components. React Hooks enable functional components to attach local state with it, and this state will be preserved by React when the component re-renders. Hence, this allows React to be used without classes. While working with function components in React, we sometimes need to add state to it. In order to achieve that (to use setState() and states), we have to convert our function component into class one. With the help of Hooks, we can use the state in Function Components, without the use of classes. A practical view There are two approaches to create a React component. One is using functions and the other is using classes. There is always a question in mind that “When do I use one v/s the other?” Let us assume we have a simple class component and then we will convert it to a functional one with hooks and see the difference. Component without Hook: Class Componentimport React, { Component } from'react';  classGreetingextendsComponent {     state = {         text: ''”     }  handleChange= (e) => {  this.setState({ text: e.target.value })     }  render() {  return (             <input  value={this.state.text}  onChange={this.handleChange}             />         )     }  }  exportdefaultGreeting; Components with Hook:Functional Component: import React, { useState } from'react';  exportdefault () => {  const [text, setText] =useState('');  return (         <input  value={text}  onChange={(e) =>{ setText(e.target.value) }}         />     );  }Advantages: Readable Lesser Code. Overall Optimized component Writing a Functional component with state Writing complex components became easier Handling events & logics in functional components. Performance boost up with Functional Components  If you disagree with any of the above, you can play with it in practice. I’m sure that would change your mind! Types of Hooks Now, let us understand the power of hooks with some cool examples that will describe some basic Hooks which are: useState() useEffect() Custom Hooks (Building Your Own Hooks) State Hook In React, we all are quite familiar with how the state is generally defined. If not, I’d recommend you to refresh your memory of State here. this.state= {     name: Steve Marley  }; While state issimilar to props, we know that state is controlled by a component. Traditionally, state is generally defined by writing a class where “this.state” is used to initialize a class. Let us take an example of class Component named (MyComponent): classMyComponentextendsReact.component {  constructor(props)  super(props);  this.state= {         name: Steve Marley     }  } In class components, it isreally hard to reuse stateful logic between components and complex class components become hard to read and even harder to understand!! React hooks help us to get rid of all that old-fashioned class stuff by making use of useState().  Now, this is important to note that in a functional component there is no concept of objects and objects being set as context (like we do in classes), so we can’t assign anything or read this.state. Instead, we call the useState Hook directly inside our functional component: This will become something like this: import{ useState } from'react'; // line 1  functionMyComponent() {  const [name, setName] =useState(‘Steve Marley');   // line 2  } Let us understand this code line by line: In line1: there is a new method imported here called useState. What is useState and how do we use it? Well, useState is the React Hook that will allow us to access and manipulate state in our existing component. Therefore, in this approach, we do not have to extend our Component as we did in previous code. And that’s it! It is worth noting that we are playing with states outside a class in the component directly as shown: import{ useState } from'react'; function MyComponent() { const [name, setName] =useState("Steve Marley"); return (<div>        <p>Heyyyyy!! {name}</p>    </div>) }Deeper explanation In class Component, we initialized the name state to 'Steve Marley' by setting this.state to { name: Steve Marley } in the constructor whereas in Functional componentthe only argument to the useState() Hook is the initial state.  Unlike with classes, the state does not have to be an object. We can keep a number or a string if that is all we need. What does useState return?It returns two variables in the array [name, setName]  where “name” is the state variable and it could be anything, and setName is the function call (can be named anything), which updates the state by providing a new state. If you are not familiar with the above syntax, please read array destructuring in JavaScript. In our example we have declared a state variable called name and set it to Steve Marley. React will remember its current value between re-renders and provide the most recent one to our function. If we want to update the current name, we can call setName. This is a way to “preserve” some values between the function calls so in other words useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React. It is worth noticing that now our component (functional component) looks pretty simple, crisp and it does not have the level of complexity that a class component normally has. Effect Hook So far, we have seen extracting stateful logic with the help of hooks and defining/setting states inside a component. But what about managing the DOM from one component to another? Or fetching the data through an API? Or handling Events? All these operations which are quite familiar to usare effects!  The Effect Hook adds the ability to perform side effects from a functional component. It is a lifecycle Hook that combinescomponentDidMount, componentDidUpdate, and componentWillUnmount in React classes but unified them into a single API. useEffect(() => {  // Do some task here  }); By calling this hook, we are simply telling our component to perform some tasks after render like Data fetching, setting up a subscription, and manually changing the DOM in our React components. Let us understand this with an example: import React, { useState, useEffect } from"react"; exportdefaultfunctionGetData() {  const [myData, setData] =useState([]);  useEffect(() => {  fetch("https://jsonplaceholder.typicode.com/todos/1")  .then(response=>response.json())  .then(myData=>setData(myData));     });  retu

Introduction to Hooks in React

55
Introduction to Hooks in React



Technological change is rapidly impacting our present and our prospects for the future, and so are frontend frameworks, which are emerging at a very fast pace these days. And in many ways, React, the most popular framework amongst the JavaScript community, is turning out to be unstoppable.   

Many of us have already played around with Hooks or have at least heard about them. But there are still many who are probably yet to take the time or have had the chance to experiment with them.  No worries, sooner or later you will find yourself diving into Hooks.  

In this article, you will learn about the term, Hooks, and the reasons why you should use them in your future projects. Furthermore, you will learn about how you can use React Hooks in the best possible manner to build some awesome features in your projects and write cleaner code.  

What exactly is a Hook? 

Hooks are just regular JavaScript functions. In layman terms, hooks provide a way to use functionalities such as context or state, which could earlier only be achieved through classes, and now can easily be done using function components. 

React Hooks enable functional components to attach local state with it, and this state will be preserved by React when the component re-renders. Hence, this allows React to be used without classes. 

While working with function components in React, we sometimes need to add state to it. In order to achieve that (to use setState() and states), we have to convert our function component into class one. With the help of Hooks, we can use the state in Function Components, without the use of classes. 

A practical view 

There are two approaches to create a React component. One is using functions and the other is using classes. There is always a question in mind that “When do I use one v/s the other?” 

Let us assume we have a simple class component and then we will convert it to a functional one with hooks and see the difference. 

Component without Hook: Class Component

import React, { Component } from'react'; 
classGreetingextendsComponent { 
   state = { 
       text: ''” 
   } 
handleChange= (e) => { 
this.setState({ text: e.target.value }) 
   } 
render() { 
return ( 
           <input 
value={this.state.text} 
onChange={this.handleChange} 
           /> 
       ) 
   } 
} 
exportdefaultGreeting; 

Components with Hook:Functional Component: 

import React, { useState } from'react'; 
exportdefault () => { 
const [text, setText] =useState(''); 
return ( 
       <input 
value={text} 
onChange={(e) =>{ setText(e.target.value) }} 
       /> 
   ); 
}

Advantages: 

  • Readable 
  • Lesser Code. 
  • Overall Optimized component 
  • Writing a Functional component with state 
  • Writing complex components became easier 
  • Handling events & logics in functional components. 
  • Performance boost up with Functional Components  

If you disagree with any of the above, you can play with it in practice. I’m sure that would change your mind! 

Types of Hooks 

Now, let us understand the power of hooks with some cool examples that will describe some basic Hooks which are: 

  • useState() 
  • useEffect() 
  • Custom Hooks (Building Your Own Hooks) 

State Hook 

In React, we all are quite familiar with how the state is generally defined. If not, I’d recommend you to refresh your memory of State here

this.state= { 
   name: Steve Marley 
}; 

While state issimilar to props, we know that state is controlled by a component. Traditionally, state is generally defined by writing a class where “this.state” is used to initialize a class. 

Let us take an example of class Component named (MyComponent): 

classMyComponentextendsReact.component { 
constructor(props) 
super(props); 
this.state= { 
       name: Steve Marley 
   } 
} 

In class components, it isreally hard to reuse stateful logic between components and complex class components become hard to read and even harder to understand!! 

React hooks help us to get rid of all that old-fashioned class stuff by making use of useState().  

Now, this is important to note that in a functional component there is no concept of objects and objects being set as context (like we do in classes), so we can’t assign anything or read this.state. Instead, we call the useState Hook directly inside our functional component: 

This will become something like this: 

import{ useState } from'react'; // line 1 
functionMyComponent() { 
const [name, setName] =useState(‘Steve Marley');   // line 2 
} 

Let us understand this code line by line: 

In line1: there is a new method imported here called useState. 

What is useState and how do we use it? 

Well, useState is the React Hook that will allow us to access and manipulate state in our existing component. Therefore, in this approach, we do not have to extend our Component as we did in previous code. 

And that’s it! It is worth noting that we are playing with states outside a class in the component directly as shown: 

import{ useState } from'react';
function MyComponent() { 
const [name, setName] =useState("Steve Marley"); 
return (<div> 
       <p>Heyyyyy!! {name}</p> 
   </div>)
}

Deeper explanation 

In class Component, we initialized the name state to 'Steve Marley' by setting this.state to { name: Steve Marley } in the constructor whereas in Functional componentthe only argument to the useState() Hook is the initial state.  

Unlike with classes, the state does not have to be an object. We can keep a number or a string if that is all we need. 

What does useState return?

It returns two variables in the array [name, setName]  

where “name” is the state variable and it could be anything, and setName is the function call (can be named anything), which updates the state by providing a new state. 

If you are not familiar with the above syntax, please read array destructuring in JavaScript

In our example we have declared a state variable called name and set it to Steve Marley. React will remember its current value between re-renders and provide the most recent one to our function. If we want to update the current name, we can call setName. 

This is a way to “preserve” some values between the function calls so in other words useState is a new way to use the exact same capabilities that this.state provides in a class. Normally, variables “disappear” when the function exits but state variables are preserved by React. 

It is worth noticing that now our component (functional component) looks pretty simple, crisp and it does not have the level of complexity that a class component normally has. 

Effect Hook 

So far, we have seen extracting stateful logic with the help of hooks and defining/setting states inside a component. But what about managing the DOM from one component to another? Or fetching the data through an API? Or handling Events? All these operations which are quite familiar to usare effects!  

The Effect Hook adds the ability to perform side effects from a functional component. It is a lifecycle Hook that combinescomponentDidMount, componentDidUpdate, and componentWillUnmount in React classes but unified them into a single API. 

useEffect(() => { 
// Do some task here 
}); 

By calling this hook, we are simply telling our component to perform some tasks after render like Data fetching, setting up a subscription, and manually changing the DOM in our React components. 

Let us understand this with an example: 

import React, { useState, useEffect } from"react";
exportdefaultfunctionGetData() { 
const [myData, setData] =useState([]); 
useEffect(() => { 
fetch("https://jsonplaceholder.typicode.com/todos/1") 
.then(response=>response.json()) 
.then(myData=>setData(myData)); 
   }); 
retu
KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

Trending blog posts

Suggested Blogs

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link https://github.com/axios/axios.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:     Using jsDelivr CDN:      It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (        User Name:      Add      )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });Conclusion I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.
5647
What is the Use of Axios in React?

While dealing with web applications in React, the... Read More

Top Web Development Trends to Watch Out for in 2021

Wondering what it would take for your business to become a pioneer in web development this year? Below are the top web development trends that are unmissable in 2020. Whether you are a full stack developer or have an organization that implements full stack, the list below can be quite handy. Web Development Trends In 20201. Voice SearchIn 2020, the dependency on voice search will surge, thanks to intelligent and nuanced digital voice assistants like Siri for iPhones and Google Assistant for Android-based phones. Ease of use and affordability have made voice search the most frequently used application among smartphone users worldwide. In the US alone, by 2021, about 122.7 million citizens are expected to use voice assistants.  For the e-commerce sector majorly, and every other business that has an online presence, voice search faculties are helping to create a loyal audience and more sales. 2. Artificial IntelligenceAI and Machine learning will show no signs of stopping this year. From analysing website behaviour to catering to the specific needs of each visitor in your target audience, machine learning and artificial intelligence would give your enterprise that much-needed edge. 3. Multi-experience In 2020, we shall see the advent of multi-experience which will let users experience an app in its entire functionality across all devices whether it’s a laptop, smartphone, smartwatch or even a tablet. This web development trend will ensure that an app is effective and engaging regardless of the device. 4. One-Page SitesAs far as one-page sites are concerned, this year there will be an increase in the number of single page websites. This is because modern browsers are more responsive to these clutter-free one-page sites. Many enterprises prefer this template as it streamlines the target audience and makes lead-generation hassle-free. 5. JavaScript TechnologyThis technology is at the heart of almost all major tech-giants. Many JavaScript frameworks have found its use in both front and backend development. Even this year, it will remain one of the most sought-after frameworks in the tech space for the development of interactive web interfaces since it’s supported by all modern browsers. 6. Blockchain Technology Despite making its presence a decade ago, blockchain technology will be one of the top trending technologies in 2020. It will be used mostly by developers to assist in cybersecurity especially during online shopping, financial transactions, digital certificates and many other areas of software development. Even crypto-currency networks will utilize the various functionalities of blockchain technology.The above trends are some of the top technologies that will dominate 2020. For professionals who are passionate about learning new technologies, staying abreast of the latest ones will be beneficial.
16035
Top Web Development Trends to Watch Out for in 202...

Wondering what it would take for your business to ... Read More

React Router: Routing Mechanism in ReactJS 

When designing a website, it is essential to be able to load different pages or modules, or to navigate to another page as per the context. React Router is the tool that supports these tasks. When implementing React Router, you may come across some issues and common problems. In this blog, we will talk about routing techniques and the underlying mechanisms.React is an extremely popular library used to create single page applications (SPAs). We can have multiple views and components in the same page, therefore, to navigate through the whole application we need to use React Router.In this post we will focus on the problems involved in using React Router, and will help you to understand the solutions.You will learn the following:IntroductionBasic RoutingHow Routing Works / Routing MechanismComponents in React Router and their explanationInstallation and StepsSource Codes and SnippetsChallenges and DebuggingConclusionIn this blog, we are using react-browser-router 2.1.2. You can check the official documentation here: https://www.npmjs.com/package/react-browser-router.In the official documentation and the API, it is mentioned as the Browser Router, but we will use the word “Router” as it can be technically aliased.1. Introduction: React Router (Browser Router)React does not provide the facility of routing when we create the react app initially. We must install it manually in our application using a package manager (npm or yarn). Later we will learn how to enable routing in our React application, but before that we need to understand the core concepts.Whenever a user changes the URL of the website, an HTTP request is sent to the server. The server recognizes the request and returns some responses, which can be a webpage or data in some forms (JSON objects, texts etc.)  The user may be redirected to another page and some other component in the same page may be loaded.  Let us take an example – when a user types a URL “localhost:3000/home”, the home page of the website should open; similarly, if the user types “localhost:3030/contact” then the contact page of the website should open. Also, if a user types some random or invalid URL, an error page or some error message should appear.React Router makes it easier for the developers to implement this approach very effectively.2. Basic RoutingThe main task of routing is to load a specific page on targeting a specific URL or path. Loading a specific page on hitting a specific URL is called basic routing. It is quite easy to jump to another page, but it can get complicated when we try to render the components inside the same page. In this state, the page does not get refreshed and therefore there is less interaction with the server; and the performance of the application is increased as the server-side rendering is reduced.  3. How Routing Works / Routing mechanismWhen we implement router in our react application, we are either looking to move to another page or load other components in the same page. To move to another page, we usually use Link inside the browser router. To load a component inside the same page, we use Route and specify the path and the component name.Inside the Router, we use Switch to switch between the different routing paths.We can use Link and Route together to load a particular component.Route is for a specific path and a particular component. Therefore, whenever a particular path is triggered, the associated component must be rendered. To use the components, we need to import them in the same file where we are using the Router.4. Components in React Router and their explanation and To handle the static requests, we use HashRouter and to handle the dynamic requests, we use BrowserRouter. We will focus on BrowserRouter in the later steps. A BrowserRouter uses regular URLs. and  Switch gives us the facility to switch between the different Routes. If no matching Route is found then the Switch renders nothing., and To create a link in our application, react provides a Link component. On the other hand, we can say that whenever we use the Link component simply (an Anchor) is rendered in the HTML document. NavLink is a special type of Link. If we want to force a particular navigation, we can use Redirect.  To know more about these components, please visit the following links: https://reactrouter.com/web/guides/primary-components5. Installation and the stepsYou must be clear with the fact that when we create a react app, the browser router is not pre-installed. So, we need to add it in the application by using npm. To implement the routing in our application, first we will create an app and make some required changes in the further steps. Let us do this from scratch.These are the essential steps which we can follow:Step #1 Create a react App:npx create-react-app my-appIf you have npm version 6+ then you can simply typenpm init react-app my-appStep #2 Move to the Directorycd my-appStep #3 Launch the appnpm startStep #4 Add Browser Router in our applicationnpm install --save react-router-domStep #5 Go to package.json and verify that the Browser Router is installed in our app6. Source codes and snippetsNow our basic project is ready and we have successfully added the Browser Router package in our application. We need to import the relevant API from the react-router-dom library to make it work. Let us move ahead and implement the rest of the steps: Step #6 Remove the unnecessary codes from the App.js. We have the following codes now:import React from 'react'; import './App.css'; function App() {   return (             ); } export default App;Step #6 Create three JS files - Home.js, Contact.js and Feedback.jsimport React from "react"; const Home = () => {   return (            This is Home Page!        ); }; export default Home;import React from "react"; const Contact = () => {   return (            This is Contact Page!        ); }; export default Contact;import React from "react"; const Feedback = () => {   return (            This is Feedback Page!        ); }; export default Feedback;Step #7 Import all the files in App.js file and start the app. You will find this output on the browser:import React from 'react'; import './App.css'; import Home from './Home'; import Contact from './Contact'; import Feedback from './Feedback'; function App() {   return (                            );  } export default App;Step #8 Now we can add the Routing part, and make some changes in the App.jsimport React from "react"; import "./App.css"; import Home from "./Home"; import Contact from "./Contact"; import Feedback from "./Feedback"; import { BrowserRouter, Route, Link } from "react-router-dom"; function App() {   return (                                             Home                                   Contact                                   Feedback                                                              ); } export default App;Explanation: Look at the App.js file carefully. We have added the Link and Route inside the Browser router which says that whenever a user clicks on the link, it renders a specific component from the given path which we have mentioned in the Route.   By default, the home page is selected. Do not forget to put exact keywords (parameters) for the home Route as it disables the partial matching for a route. You can play around with the code and find out some interesting observations.   You can see in the address bar that whenever we click on the Contact and Feedback link, their respective URLs are reflected in the address bar. You can manually fill the same URL and trigger it, and it loads the respective pages. It is called basic or simple routing.  7. Challenges and debuggingI have gone through other blogs and tutorials where I have seen that they have aliased the BrowserRouter to Router. So do not get confused with this term. Both are similar and I am sure that you are aware about the Aliases for the packages.You might face issues while using the BrowserRouter, Link and Route and therefore make sure that the package is installed. You can verify it in the package.json file.Make sure that you provide the correct path and component name in the Route.You can find the helpful documentation and resources here: https://reactrouter.com/web/api/BrowserRouterConclusionIt is amazingly easy to use React Routing in your applications. It makes the UI more appealing and dynamic. You must specify the correct path and the respective components in the route component to make it work correctly. Before implementing the approaches, a basic understanding of the component and the hierarchy of the react components is necessary. There may be changes in the API or in the versions, therefore it is always better to use the official documentation to understand the usage.
React Router: Routing Mechanism in ReactJS 

When designing a website, it is essential to be ab... Read More