Hooks of React Router 5+ Examples

Last updated on by Digamber

React Router 5 Hooks tutorial with or without routing examples.

Single page application is not a new buzz in town. Rather, every React developer going gaga over this. React is a powerful yet flexible option to build a SPA (Single page application).

The core functionalities of React makes it the best choice among other front-end frameworks. React Router Hooks are lucrative in building routing mechanism in React apps.

React Router hooks API are the tools that make your routing work easy to go with.

In this tutorial, we are going to tell you about 4 awesome Hooks of React Router which can help you implement routing in your React app.

Before we begin, let me make sure we must be working with React 16.8+ version to deal with Hook. You can go with pre-defined third-party hooks or router hooks API.

Please note that you need to be using React 16.8+ version to use hooks either built-in or custom third-party hooks, including the router hooks.

Install React Application

To fight a battle, we need a war ground, likewise to see how React Router Hooks work we need a React web app ready on our working machine.

To create such an app, you must run the following command from your terminal window.

npx create-react-app react-router-hooks

Get to the project root:

cd react-router-hooks

Run the app in the browser:

npm start

Install React Router Package

There are two ways through which you can install React Router library, either npm or yarn. We are dealing with a web application so that we will shoot the following command from the terminal.

npm install react-router-dom

Add the given below code in src/App.js file.

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function App() {
  return (
    
  );
}

Primordial Method of React Routing 5/4

This example walks you through about the time when hooks were not everybody’s cup of tea.

Before creating a path in React, we needed to import the component and declare the component name within the Route component.

<Route path="/" component={Home} />

When you visit the path=”/”, then the defined component will be accessed.

You can access routing props by defining some other props such as history, match and location. In some case, you may require to add additional props so don’t worry just define render prop to declare the extra properties.

<Route path="/" render={({ match }) => <Products match={match} mine={true} />}>

Hooks in React Router 5

As you can see, we don’t have to pass props deliberately. It has been metamorphosed by React team now you can add much more flexibility with extra props to the component you need to render.

Here is the example of React Router with hooks API.

<Route path="/">
  <Home />
</Route>

Now, the question emerges from nowhere that we haven’t declared the props so how can we perfectly align the match, location or history to access the router hooks props.

The useHistory Hook

The useHistory hook gives you full access to the history object or prop via React Router.

Import the useHistory hook module from ‘react-router-dom’ package.

import { useHistory } from 'react-router-dom';

function Products() {
  const history = useHistory();
  return <button onClick={() => history.push('/products')}>Products</button>;
}

You can use history object with push, replace types of methods.

The useLocation Hook

To use history hook, you must import it; first, the usehistory hook gives access to the history object.

import { useLocation } from 'react-router-dom';

function Product() {
  const location = useLocation();

  useEffect(() => {
    const currentPath = location.pathname;
    const searchParams = new URLSearchParams(location.search);
  }, [location]);

  return <p>Product</p>;
}

useParams in React

What if you need to access the router params from the URL parameter, and what about accessing the search parameter in the URL.

Don’t worry, and we can import the useParams, Route service from ‘react-router-dom’ package.

import { useParams, Route } from 'react-router-dom';

function Product() {
  const { name } = useParams();
  return <p>{name}</p>;
}

function Home() {
  return (
    <>
      <nav>
        <Link to={`/product/shoes`}>Shoes</Link>
      </nav>
      <main>
        <Route path="/product/:tshirts">
          <Product />
        </Route>
      </main>
    </>
  );
}

The Bottom Line

We have explained about using useParams, useLocation and useHistory hooks, i hope you must have understood the basic concept and usage of hooks in React.