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

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.

Similar Reads

Pre-requisite:

NPM & Node JS React JS React JS Router React JS Types of Routers...

Hooks Of React Router 5:

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

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....

useParams Hook:

...

useLocation Hook:

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

useRouteMatch Hook :

...

Reason to use React Router Hooks

...

Contact Us