Using React Router

Using React Router Hooks Part-1

React Hooks were introduced with the release of React 16.8.0 to much excitement. With Hooks, developers can write cleaner components with less boilerplate compared to a class component. Many popular React packages are adding support for Hooks so developers can leverage their APIs in functional components.

React Router, the go-to routing solution for React Apps, added Hooks support in its version 5 release. These React Router Hooks provide developers with new ways to handle the router state.

In this tutorial, we’ll show you how to use Hooks with React Router and minimize code lines in a component.

How Hooks work with React Router

To demonstrate how Hooks work, we’ll create a React project and set up the pages.

To create a React app, run the following command:

Note that router-hooks-demo is the name of the app for this guide; you can change the name as you wish.

Next, add the react-router-dom package:

Import BrowserRouter, Link, Route, and Switch components from the react-router-dom package. These components will be used to configure client-side routing in the React app.

For this demo, you’ll only have two routes, or pages: the home page and user page. You’ll mainly be working on the user page.

In the App component, create a navigation bar section and add hyperlinks to the pages using the Link component. On the webpage, the Link component gets rendered as a <a> tag.

Next, add the Switch and Route component, and wrap everything in the BrowserRouter component.

The BrowserRouter component enables the client-side routing feature and handle the routing logic using the browser history API. The Route component renders the page UI when the route path matches the active URL. The Switch component only allows the first matched path to be rendered.

If you have a bunch of Route components that match the same URL, you’ll end up rendering all the routes, which is not expected. Only one route should be rendered for a URL.

The final App.js file should look like this:

Why React Router Hooks are useful

Let’s say you need to access the current pathname of the URL inside a page component. Before Hooks, you would have to pass the page component to the component prop of the Route component. Then the Route component would inject with route props: match, location, and history.

This is fine, but the component becomes harder to read and it’s difficult to understand how the props are injected when it comes to maintaining the project. The React Router authors added Hooks support so the page components can access history, location, and match objects without having to pass the page component as a component prop in the Route component.

A tech enthusiast and a die hard lover of JavaScript.