How to Use the useLocation Hook in React Router
This article provides a straightforward guide on how to implement and
use the useLocation hook from React Router in your web
applications. You will learn what the useLocation hook is,
how to import and initialize it, and see a practical code example
demonstrating how to access URL pathnames, query parameters, and custom
state.
What is the useLocation Hook?
The useLocation hook is a built-in feature of the
react-router-dom library. It returns the current
location object, which represents the URL of the page your
application is currently rendering. This hook is highly useful for
triggering page-view analytics, conditionally rendering components based
on the current route, or reading query strings and navigation
states.
The location object contains the following key
properties: * pathname: A string representing the path
of the URL (e.g., /profile). * search: A
string representing the query parameters (e.g., ?id=123). *
hash: A string representing the URL hash fragment
(e.g., #settings). * state: An optional
developer-defined state object passed from a navigation link or
action.
Step-by-Step Implementation
To use the useLocation hook, ensure your React
application has react-router-dom installed and that the
component using the hook is nested inside a Router component (such as
BrowserRouter).
Step 1: Import the Hook
Import useLocation from the
react-router-dom package at the top of your component
file.
import { useLocation } from 'react-router-dom';Step 2: Initialize the Hook
Call the hook inside your functional component to gain access to the
current location object.
const location = useLocation();Step 3: Access URL Data
You can now read the properties of the location object
to react to URL changes.
Practical Code Example
Below is a complete, practical example of a React component that
utilizes useLocation to display the current path, parse
query parameters using URLSearchParams, and read state sent
during navigation.
import React from 'react';
import { useLocation } from 'react-router-dom';
function CurrentRouteDisplay() {
const location = useLocation();
// Parse query parameters (e.g., ?search=react&sort=asc)
const queryParams = new URLSearchParams(location.search);
const searchQuery = queryParams.get('search');
return (
<div style={{ padding: '20px', border: '1px solid #ccc' }}>
<h3>Current Navigation Details</h3>
<p><strong>Pathname:</strong> {location.pathname}</p>
<p><strong>Search Query String:</strong> {location.search || 'None'}</p>
<p><strong>Extracted Search Param:</strong> {searchQuery || 'No search query'}</p>
<p><strong>Hash:</strong> {location.hash || 'None'}</p>
{/* Display custom state if passed from a previous Route */}
<p>
<strong>Navigation State:</strong>{' '}
{location.state ? JSON.stringify(location.state) : 'No state passed'}
</p>
</div>
);
}
export default CurrentRouteDisplay;Passing State to useLocation
You can pass data to the useLocation hook of a
destination page when using the Link component or the
useNavigate hook.
Using a Link component:
import { Link } from 'react-router-dom';
<Link to="/profile" state={{ fromDashboard: true }}>
Go to Profile
</Link>Using the useNavigate hook:
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/profile', { state: { fromDashboard: true } });When the user navigates to /profile,
location.state in the destination component will resolve to
{ fromDashboard: true }.