Open In App

What are the React Router hooks in React v5?

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information about the desired URL and navigating through web pages.

We will discuss the different React Router hooks in React v5:

Prerequisites:

useParams

useParams hook is a functional component hook that is used to extract dynamic route parameters from the current or active URL. The term Params in ‘useParams’ defines parameters that are used to retrieve data from a URL. useParams retrieves an object containing key-value pairs where the keys are parameter names defined in the route path and the values are corresponding parameter values from that URL.

It’s important to define the expected parameters in the route path using colons (:). If a parameter is not present in the URL its respective value in the object will be “undefined“.

Example: Below is an example of useParams. In the below code the useParams() retrieves the parameters or values of the URL and destructures them as “productId” and “color”. Parameters of URL are ‘123’ and ‘blue’.

JavaScript
import {
    BrowserRouter,
    Routes,
    Route
} from 'react-router-dom';
import MyComponent from './MyComponent';

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/products/:productId/:color"
                    element={<MyComponent />} />
            </Routes>
        </BrowserRouter>
    );
}

function MyComponent() {
    const { productId, color } = useParams();

    return (
        <div>
            <p>Product ID: {productId}</p>
            <p>Color: {color}</p>
        </div>
    );
}

export default App;

Output :

output-1


useLocation

useLocation retrieves the current URL information as an object, this object changes whenever the user navigates to a new URL. Object provides properties like pathname, search string and a hash fragment. useLocation hook can also be used in cases like triggering events by a change in URL.

useLocation only reflects the current URL and doesn’t triggger re-renders when the URL changes on its own. If you need to respond to your URL changes , consider using the “useEffect” hook along with the “useLocation” hook.

Example: Below is an example of useLocation. In the below code the “location.search() ” returns the entire string after ” ? ” from the URL.

JavaScript
import {
    BrowserRouter,
    Routes,
    Route
} from 'react-router-dom';
import MyComponent from './MyComponent';

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<MyComponent />} />
                <Route path="/products/:productId"
                    element={<MyComponent />} />
            </Routes>
        </BrowserRouter>
    );
}

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

    return (
        <div>
            <p>Current Path: {location.pathname}</p>
            <p>Search String: {location.search}</p>
        </div>
    );
}
export default App;

Output:

output-2

useHistory

useHistory hook provides access to history object that manages the history stack. History stack contains all the URL’s visited by the user. “useHistory” hook grants access to history instance which is created by React router. Using the history instance users can navigate from one URL to another , it also allows user to move back and forth using browser buttons or custom logic.

Methods of useHistory hook :

  • history.push(path) : Navigates to a new URL by pushing it onto the history stack.
  • history.replace(path) : Replaces the current URL in the history stack with the provided path. This can be useful in cases when we don’t want to revisit the same page again by navigating backwards.
  • history.goBack() : Navigates to the previous URL in the history stack, similar to brower’s backward button.
  • history.goForward() : Navigates to next URl in the history stack, similar to browser’s forward button

*Note : “useHistory()” hook will only work in the React-router-dom v5 but not in v6 , as it is replaced with “useNavigate()” hook.

Example: Below is an example of useHistory. Clicking the “Logout ” button displays a message (“User logged out “) on to the console and also redirects you to the ‘login page’.

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

function Dashboard() {
    const history = useHistory();

    const handleLogout = () => {
        // Simulate some logout logic (e.g., clear user data)
        console.log('User logged out');

        // Redirect user to login page after logout
        history.push('/login');
    };

    return (
        <div>
            <h1>Welcome to the Dashboard</h1>
            <button onClick={handleLogout}>Logout</button>
        </div>
    );
}

export default Dashboard;

Output :

output3-1

outpu3-2

Console view

useRouteMatch

The “useRouteMatch” hook tries to find a match with the current URL and returns an object through which you can access information of the matched route. This information includes paths, url parameters and more.

*Note : “useRouteMatch()” hook will only work in the React-router-dom v5 but not in v6 , as it is replaced with “useMatch()” hook.

Example: Below is an example of useRouteMatch In the above example I’ve used a URL that is “/posts/:123” which is being compared with the ‘/posts/:postId ‘ using “useRouteMatch()” and returns the data present in it.

JavaScript
// App.js

import * as React from "react";
import {
    BrowserRouter,
    Route,
    Routes
} from "react-router-dom";
import MyComponent from './MyComponent';

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/posts/:postId"
                    element={<MyComponent />} />
            </Routes>
        </BrowserRouter>
    );
}

export default App;
JavaScript
// MyComponent.js

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

function MyComponent() {
    const { postId } = useParams(); // Access URL parameter
    const match = useRouteMatch('/posts/:postId'); // Match route pattern

    // Display message if route doesn't match pattern
    if (!match) {
        return <div>This route does not match a blog post.</div>;
    }

    // Simulate fetching post data (replace with your actual logic)
    const postData = {
        id: postId,
        title: `Blog Post`,
        content: 'This is the content of the blog post.'
    };

    return (
        <div>
            <h1>PostId {postData.id}</h1>
            <h1>{postData.title}</h1>
            <p>{postData.content}</p>
        </div>
    );
}

export default MyComponent;

Output :
output-4



Similar Reads

When is it best to use custom hooks instead of built-in React hooks?
Custom hooks in React are useful when you want to extract and reuse stateful logic across multiple components. While built-in React hooks like useState, useEffect, and useContext cover many common scenarios, there are cases where creating custom hooks can enhance code organization, readability, and reusability. When to Choose for Custom Hooks in Re
2 min read
React-Router Hooks
React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single page. Pre-requisite: NPM &amp; Node JSReact JSReact
11 min read
How to Create Custom Router with the help of React Router ?
To create a custom Router using React Router, you can define a new component that utilizes the Router's 'BrowserRouter' along with 'Route' components to handle different paths and render corresponding components. Use 'Link' components for navigation within your application, providing a seamless routing experience in your React application. What is
3 min read
Explain the new feature of React hooks introduced in React v16.8
React v16.8 is no less than a miracle for all the React developers because this version of React introduced hooks to all of us. Before its release, the developer community was tired of using class components but they still had to use them because the functional component does not provide many features that the class component provides. But after ho
7 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
What are React Hooks, and why were they added to React?
React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components, making them more powerful and flexible. Hooks Addr
2 min read
Implement Nested Routes in React.js - React Router DOM V6
Nested routes in React JS are implemented using the outlet in React Router Dom. Routing in React not only provides routing for the pages but also for switching the content inside that page. Nested routes implement this by defining Routes for Child components inside parent route components. Prerequisites: React JSReact RouterReact Router DomApproach
4 min read
How does React Router handle navigation in a React application?
React RouterĀ is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. Let us create a simple application to React to understand how the React Router works React Router simplifies navigation in React applicat
3 min read
Implementing React Router with Redux in React
This article explores implementing React Router with Redux for enhanced state management and routing in React applications. Table of Content What is React Router and Redux?Approach to implement React Router in ReduxSteps to Setup the React AppWhat is React Router and Redux?React Router facilitates routing in React apps, managing component rendering
3 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read