Skip to content
CannonReactHooks

useLocation Hook

Introduction

A custom React Hook for tracking and managing the current browser location.

Play

Usage

import { useLocation } from "@cannonui/reacthooks";
const LocationDisplay = () => {
  const location = useLocation();

  return (
    <div>
      <pre>{JSON.stringify(location, null, 2)}</pre>
    </div>
  );
};
const TestUseLocation = () => {
  return (
    <div>
      <LocationDisplay />
    </div>
  );
};
export default TestUseLocation;

Return Value

The hook returns an object of type Location containing various properties related to the current browser location.

Properties of Location

NameTypeDescription
triggerstringThe trigger that caused the location change (e.g., “popstate” or “hashchange”).
stateRecord<string, any> | nullThe state associated with the current location (from the browser history API).
lengthnumberThe length of the browser history.
hashstringThe hash portion of the current location (e.g., “#section1”).
hoststringThe host and port of the current location (e.g., “example.com:8080”).
hostnamestringThe host name of the current location (e.g., “example.com”).
hrefstringThe full URL of the current location.
originstringThe origin of the current location (e.g., ”http://example.com:8080”).
pathnamestringThe pathname portion of the current location (e.g., “/products”).
portstringThe port of the current location (e.g., “8080”).
protocolstringThe protocol of the current location (e.g., “http:” or “https:”).
searchstringThe query string portion of the current location (e.g., “?id=123”).

Features

  • Tracks and manages the current browser location.
  • Provides various properties related to the current location, such as pathname, search, hash, host, and more.
  • Supports detecting location changes triggered by history API (popstate) and hash changes (hashchange).

Example

In this example, we have a component called TestUseLocation that uses the useLocation Hook to track and display the current browser location. The LocationDisplay component displays the location properties obtained from the useLocation Hook.

Use Scenario

The useLocation Hook is useful in scenarios where you need to access and react to changes in the current browser location. It allows you to build location-aware React components and implement dynamic behavior based on the URL or browser history changes. For example, you can use it to implement client-side routing, conditionally render components based on the current URL, or update the application state when the user navigates through different routes.