What is useLocation Hook in React Router?

This article provides a comprehensive guide to the useLocation hook in React Router, explaining its purpose, core properties, and practical applications. You will learn how to access the current URL’s location object, retrieve route state, and implement common use cases like page tracking and dynamic styling based on the active path.

Understanding the useLocation Hook

The useLocation hook is a built-in hook provided by the react-router-dom library. It returns the current location object, which represents the URL of the page the user is currently on. You can think of it as a React-friendly alternative to the native browser window.location object.

Whenever the URL changes, the useLocation hook triggers a re-render, ensuring your component always has access to the most up-to-date routing information.

The Location Object Structure

The object returned by useLocation contains several useful properties:

Basic Implementation

To use the useLocation hook, you must import it from react-router-dom and call it inside a component that is rendered within a <Router> context.

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

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

  return (
    <div>
      <p>Current Path: {location.pathname}</p>
      <p>Search Query: {location.search}</p>
    </div>
  );
}

export default CurrentRouteDisplay;

Common Use Cases

1. Accessing State Passed via Navigation

You can pass custom data when navigating between routes using the Link component or the navigate function, and retrieve it using useLocation.

Sending state:

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

const navigate = useNavigate();
navigate('/dashboard', { state: { fromLogin: true } });

Retrieving state:

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

const location = useLocation();
const fromLogin = location.state?.fromLogin;

2. Tracking Page Views (Analytics)

Since useLocation updates on every route change, you can combine it with the useEffect hook to trigger page-view analytics whenever a user navigates.

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

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

  useEffect(() => {
    // Replace with your analytics provider (e.g., Google Analytics)
    console.log(`Page viewed: ${location.pathname}`);
  }, [location]);

  return null;
}

3. Parsing Query Parameters

You can parse the search string to extract query parameters using the native URLSearchParams API.

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

function SearchResults() {
  const { search } = useLocation();
  const queryParams = new URLSearchParams(search);
  const term = queryParams.get('query');

  return <p>Showing results for: {term}</p>;
}