React Router Hooks

Learn via video courses

Overview

Popular React package React-Router provides single-page routing and is widely used for client-side routing. It offers several component APIs (such as Route, Link, etc.) that can be used in your React applications to render numerous components according to the URL pathnames of the single page.

Introduction

React is a JavaScript package that allows you to create user interfaces. Using React Router, we can also expand it to create multi-page applications. Our React projects can use this third-party library to allow routing.

React Hooks are basic JavaScript functions that can be used to separate code snippets from functional components. Hooks can handle side effects and can be stateful.

Fortunately, the router that controls networking data is different from the react router. However, there are many similarities between the React Router and a networking router. We can direct users to the appropriate component with the aid of the React Router. For instance, we can create a single-page application (SPA) using client-side routing that enables page switching without refreshing the browser.

Prerequisites

How Hooks work with React Router

We'll build up the pages in a React application and construct a project to show how Hooks function.

Run the subsequent command to produce a React app:

For this article, the app's name is demo-app; however, you are free to alter it.

After that, install the react-router-dom package:

Add the react-router-dom package's BrowserRouter, Route, Link, and Switch components to your program. The client-side routing of the React application will be set up using these components.

For this demonstration, you will just have two routes or pages: the login page and the dashboard page.

Create a section for the navigation bar using the App component's Link component, then use the Link component to link to the pages. The Link component is rendered as an <a> tag on the webpage.

The Switch and Route components should then be included, followed by the BrowserRouter component to wrap the components.

The front-end-side routing feature is enabled by the BrowserRouter component, which also handles the routing logic utilizing the browser history API. When the route path fits the current URL, the page UI is rendered by the Route component.  Only the first path that matches can be shown using the Switch component.

It is not what you would expect to happen if you have many Route components that all match the same URL. For each URL, just one rendering should be made.

The complete App.js file ought to resemble the following:

Hooks Of React Router 5

a. useHistory

One of React Router's best-known hooks is useHistory. You can use it to get the history instance that React Router uses. You can reroute people to a different page using the history instance. A stack called History Stack is used by React Router to store all of the entries that have been visited by the user in the history instance that is created by the tool.

Syntax

Properties

  1. length: It gives back an integer that represents the number of entries in the history stack.

  2. action: It returns a string that represents the current action (such as PUSH, POP or REPLACE).

  3. location: It provides a corresponding object that reflects the current location. It might possess the following properties:

    a. pathname: A string specifying the path of the URL b. search: A string specifying the URL query string c. hash: A string specifying the URL hash fragment d. state: The object containing location-specific state when a location was pushed onto the stack through e.g. push(path, state). It is only accessible in memory history and the browser.

b. useParams

This hook produces an object containing each of the URL's parameters.

Syntax

c. useLocation

This hook gives back the location object that the react-router uses. This object, which represents the current URL, cannot be changed. The useLocation() hook always returns a fresh location object whenever the URL changes. It can be used, for example, to extract the query section from the URL and perform an action based on them. A string holding the query parameters of the URL is returned by the location object's search property.

Syntax

d. useRouteMatch

It returns an object with all the details about how the current URL and the Route path matched. Nesting Routes and Links is possible with the useRouterMatch hook.

Properties

  • params: The variable portion of the URL is included in this object.
  • isExact: This boolean value, which states if the full URL matches the specified Router path, is true or false.
  • path: The path pattern is contained in this string.
  • URL: The URL component that was successfully matched as a string. It can be applied to nested routes and links.

Syntax

Why React Router Hooks are Helpful

Say you want to obtain the URL's current pathname from within a page component. Before Hooks, you would need to send the page component to the Route component's component prop. Then the match, location, and history route props would be injected into the route component.

This is acceptable however when it comes to project maintenance, it becomes more difficult to read the components and explain how props are passed into the route component. Prior to React Router 5, the only way to directly give the location, match, and history instances as props to the component was to use the render prop. The hooks feature was implemented by the developers of React Router so that page components may access history, location, and match data without requiring the page component to be passed as a prop in the Route component.

Conclusion

  • Routing is required for Single Page Applications (SPAs) to browse through pages and establish the state.
  • Router hooks greatly simplify the process. You may now easily and elegantly retrieve the history, location, or parameters.
  • The useHistory hook allows us to access the history instance without having to pull it from props.
  • The useParams hook allows us to retrieve the URL parameter without using the props object.
  • Using the useLocation hook, an object representing the current URL is returned.
  • It is not necessary to explicitly give the components' props when utilizing the useHistory, useLocation, and useRouteMatch hooks to access the history, and location directly, and match objects respectively.
  • Remember: These react-router hooks require React 16.8 or higher to function. Also, don't forget to use them within functional components.