Open In App

React-Router Hooks

Improve
Improve
Like Article
Like
Save
Share
Report

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:

 Note: You need to have React >= 16.8 installed on your device, otherwise the hooks won’t work.

Hooks Of React Router 5:

These are 4 React Router Hooks in v 5 that you can use in your React applications:

  • useHistory
  • useParams
  • useLocation
  • useRouteMatch

We will discuss all the hooks in detail with proper examples:

useHistory Hook:

This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page. The history instance created by React Router uses a Stack( called “History Stack” ), that stores all the entries the user has visited.

Syntax :

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

// Inside a functional component
export default function SomeComponent(props){
// The useHistory() hook returns the history
// object used by React Router
const history = useHistory();
}

The history object returned by useHistory() has various properties and methods.

Properties: 

  • length: Returns a Number. The number of entries in the history stack
  • action: Returns a string representing the current action (PUSH, REPLACE, or POP).
  • location: Returns an object that represents the current location. It may have the following properties:
    • pathname: A string containing the path of the URL
    • search: A string containing the URL query string
    • hash: A string containing the URL hash fragment
    • state: An object containing location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.

Methods:

  • push(path, [state]): Pushes a new entry onto the history stack. Useful to redirect users to page
  • replace(path, [state]): Replaces the current entry on the history stack
  • go(n): Moves the pointer in the history stack by n entries
  • goBack(): Equivalent to go(-1).
  • goForward(): Equivalent to go(1).
  • block(prompt): Blocks navigation. It takes a callback as a parameter and invokes it after the navigation is blocked. Most useful when you want to first confirm if the user actually wants to leave the page.

Example: Suppose we have a React project created using “create-react-app” having the following project structure.

Project structure:

react-router-hooks-tutorial/
|--public/
|--src/
| |--components/
| | |-->Home.js
| | |-->ContactUs.js
| | |-->AboutUs.js
| | |-->LogIn.js
| | |-->Profile.js
| |-->App.js
| |-->App.css
| |-->index.js
| |-->index.css
| |-->... (other files)
|-- ...(other files)

Suppose, inside the “LogIn.js”, we have a “LogIn” component that renders the log-in page. The LogIn component renders two input fields, one for the username and another for a password. When the user clicks the login button, we want to authenticate the user and redirect the user to his/her profile page.

Javascript




// Filename - LogIn.js
 
import { useHistory } from "react-router-dom";
import { useState } from "react";
 
// A function that authenticates the users
function authenticateUser(userName, password) {
    // Some code to authenticate the user
}
 
// Hooks must be used inside a functional component
export default function Login(props) {
    //Creating a state variable
    const [userName, setUserName] = useState("");
    const [password, setPassword] = useState("");
 
    // Accessing the history instance created by React
    const history = useHistory();
 
    // Handle the user clicks the login button
    const handleClick = () => {
        // Authenticate the user
        authenticateUser(userName, password);
 
        // When the authentication is done
        // Redirect the user to the `/profile/${userName}` page
        // the below code adds the `/profile/${userName}` page
        // to the history stack.
        history.push(`/profile/${userName}`);
    };
 
    return (
        <div>
            <input
                type="text"
                value={userName}
                onChange={(e) => {
                    setUserName(e.target.value);
                }}
                required
            />
            <input
                type="text"
                value={password}
                onChange={(e) => {
                    setPassword(e.target.value);
                }}
                required
            />
            <button type="submit" onClick={handleClick}>
                {" "}
                Log In{" "}
            </button>
        </div>
    );
}


Output:

Log in page

Check the Login component carefully, the “handleClick” function takes the username and password and calls the “authenticateUser” function which somehow authenticates the user. When the authentication is done, we want to redirect the user to the “profile/John” (suppose the username is “John”) page. That’s what the last line of handleClick function does. “useHistory()” hook returns the history instance created by React Router, and history.push(“/profile/John”) adds the given URL to the history stack which results in redirecting the user to the given URL path. Similarly, you can use other methods and parameters of the history object as per your need.

Check the next hook to see how the redirection to a dynamic URL works.

useParams Hook:

This hook returns an object that consists of all the parameters in URL. 

Syntax: 

import { useParams } from "react-router-dom";

// Inside a functional component
export default function SomeComponent(props){
const params = useParams();
}

These URL parameters are defined in the Route URL. For example, 

<Route path="/profile/:userName" component={Profile} />

The colon(“:”) after “/profile/” specifies that “userName” is actually a variable or parameter that is dynamic. For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter “userName”. So, in this case, the object returned by useParams() is:

{
userName: "johndoe"
}

Example: After the login we want our user to be redirected to the “profile/userName” URL. The userName depends on the user’s given name.  So, we need to set the URL path dynamically based on the user given userName. This is easy to do, we need to update the App.js file a little.

Javascript




// Filename - App.js
 
import { Route, Switch } from "react-router-dom";
import Home from "./components/Home";
import ContactUs from "./components/ContactUs";
import LogIn from "./components/LogIn";
import AboutUs from "./components/AboutUs";
import Profile from "./components/Profile";
 
export default function App() {
    return (
        <div className="App">
            <Switch>
                <Route path="/" exact>
                    <Home someProps={{ id: 54545454 }} />
                </Route>
                <Route path="/about">
                    <AboutUs />
                </Route>
                <Route path="/contact-us">
                    <ContactUs />
                </Route>
                <Route path="/log-in">
                    <LogIn />
                </Route>
                {/* userName is now a variable */}
                <Route path="/profile/:userName">
                    <Profile />
                </Route>
            </Switch>
        </div>
    );
}


Javascript




// Filename - Profile.js
 
import { useParams } from "react-router-dom";
 
export default function Profile(props) {
    // useParams() returns an object of the parameters
    // defined in the url of the page
    // For example, the path given in the Route component
    // consists of an "userName" parameter
    // in this form ---> "/profile/:userName"
    const { userName } = useParams();
 
    return (
        <div>
            <h1> Profile of {userName}</h1>
 
            <p> This is the profile page of {userName}</p>
        </div>
    );
}


Output: Now if you now go to the log-in page and click the login button with userName “John”, then you will be redirected to the “profile/john” page.

useLocation Hook:

This hook returns the location object used by the react-router. This object represents the current URL and is immutable. Whenever the URL changes, the useLocation() hook returns a newly updated location object. Some of its use includes extracting the query parameters from the URL and doing something depending on the query parameters. The “search” property of the location object returns a string containing the query part of the URL.

Syntax :

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

// Inside functional component
export default function SomeComponent(props){
const location = useLocation();
}

Note: history.location also represents the current location, but it is mutable, on the other hand, the location returned by useLocation() is immutable. So, if you want to use the location instance, it is recommended to use the useLocation() hook.

Example: The useLocation() is very useful to get and use the query parameters defined in the URL. In the below code we have used the useLocation hook to access the query parameters. Then we parsed it using the URLSearchParams constructor.

Javascript




// Filename - Profile.js
 
import { useLocation } from "react-router-dom";
 
export default function Profile(props) {
    const location = useLocation();
 
    // location.search returns a string containing all
    // the query parameters.
    // Suppose the URL is "some-website.com/profile?id=12454812"
    // then location.search contains "?id=12454812"
    // Now you can use the URLSearchParams API so that you can
    // extract the query params and their values
    const searchParams = new URLSearchParams(
        location.search
    );
 
    return (
        <div>
            {
                // Do something depending on the id value
                searchParams.get("id") // returns "12454812"
            }
        </div>
    );
}


Output :

Displays the given query id

useRouteMatch Hook :

Returns a match object that contains all the information like how the current URL matched with the Route path. 

Properties:

  • params: This is an object that contains the variable part of the URL.
  • isExact: This is a boolean value, indicating whether the entire URL matched with the given Router path.
  • path: A string that contains the path pattern.
  • URL: A string that contains the matched portion of the URL. It can be used for nested <Link />s and <Route />s.

Syntax :

import { useRouteMatch } from "react-router-dom";

// Inside functional component
export default function SomeComponent(props) {
const match = useRouteMatch();
}

Example: The useRouterMatch hook can be used in creating nested Routes and Links. The following code renders the Profile page of the user when the current URL path entirely matches the given Route path, otherwise, it renders another Route that renders the User’s followers page when the current URL path is  “profile/:userName/followers”.

Javascript




// Filename - Profile.js
 
import {
    Link,
    Route,
    useParams,
    useRouteMatch,
} from "react-router-dom";
 
export default function Profile(props) {
    // useParams() returns an object of the parameters
    // defined in the url of the page
    // For example, the path given in the Route component
    // consists of an "userName" parameter
    // in this form ---> "/profile/:userName"
    const { userName } = useParams();
    const match = useRouteMatch();
 
    return (
        <div>
            {match.isExact ? (
                <div>
                    <h1> Profile of {userName}</h1>
 
                    <p>
                        {" "}
                        This is the profile page of{" "}
                        {userName}
                    </p>
 
                    <Link to={`${match.url}/followers`}>
                        Followers
                    </Link>
                </div>
            ) : (
                <Route path={`${match.url}/followers`}>
                    <div>My followers</div>
                </Route>
            )}
        </div>
    );
}


Output:

If you click the follower’s link, you will be redirected to the “/profile/John/followers” page, and as the entire URL path “profile/John/followers” does not match the given Route path i.e. “profile/;userName”, so the div element inside the Route component gets rendered.

Remember You need to have React 16.8 or higher in order to use these react-router hooks. Also, don’t forget to use them inside functional components.

Reason to use React Router Hooks

Before React Router 5:

By default, while using the component prop (<Route component={} />), React router passes three props(match, location, history) to the component that the Route renders. That means, if you, for some reason, want to access the history or location instance used by React router, you can access it through the default props.

But if you pass your custom props to your components then the default props get overridden by your custom props. As a result, you will not have any further access to the history object created by React Router. And before React Router 5, there was no way other than using the render prop (<Router render={} />) to explicitly pass the location, match, and history instance as props.

Javascript




// Filename - App.js
 
import "./styles.css";
import { Route, Switch } from "react-router-dom";
import About from "./components/About";
 
export default function App() {
    return (
        <div className="App">
            <Switch>
                // In this case, you have to use render //
                instead of component and explicitly // pass
                the props
                <Route
                    path="/about"
                    render={({
                        match,
                        location,
                        history,
                    }) => (
                        <About
                            match={match}
                            location={location}
                            history={history}
                            someProps={{ id: 21254 }}
                        />
                    )}
                />
            </Switch>
        </div>
    );
}


Javascript




// Filename - About.js
 
import { useLocation } from "react-router-dom";
 
export default function (props) {
    // Accessing the location and history
    // through the props
    const location = props.location;
    const history = props.history;
    return <div>// Some content</div>;
}


With React Router 5 Hooks:

Now with React Router 5, you can easily pass your custom props to the rendering component.

Though in this case also those three props (match, location, history) don’t get past the rendered components automatically, we can now use the hooks provided by React Router 5, and we don’t need to think about the props anymore. You can directly access the history object by using the useHistory hook, location object with useLocation hook, and match the object with useRouteMatch hook, and you don’t have to explicitly pass the props to the components.  

Javascript




// Filename - App.js
 
import "./styles.css";
import { Route, Switch } from "react-router-dom";
import Home from "./components/Home";
import ContactUs from "./components/ContactUs";
import LogIn from "./components/LogIn";
import AboutUs from "./components/AboutUs";
 
export default function App() {
    return (
        <div className="App">
            <Switch>
                <Route path="/" exact>
                    <Home someProps={{ id: 54545454 }} />
                </Route>
                <Route path="/about">
                    <AboutUs />
                </Route>
                <Route path="/contact-us">
                    <ContactUs />
                </Route>
                <Route path="/log-in">
                    <LogIn />
                </Route>
            </Switch>
        </div>
    );
}


Javascript




// Filename - Home.js
 
import {
    useHistory,
    useLocation,
    useParams,
    useRouteMatch,
} from "react-router-dom";
 
export default function Home(props) {
    // Access the history object with useHistory()
    const history = useHistory();
 
    // Access the location object with useLocation
    const location = useLocation();
 
    // Access the match object with useRouteMatch
    const match = useRouteMatch();
 
    // Extract the URL parameters with useParams
    const params = useParams();
 
    return <div>{/* Some code */}</div>;
}




Last Updated : 28 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads