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
Name | Type | Description |
---|---|---|
trigger | string | The trigger that caused the location change (e.g., “popstate” or “hashchange”). |
state | Record<string, any> | null | The state associated with the current location (from the browser history API). |
length | number | The length of the browser history. |
hash | string | The hash portion of the current location (e.g., “#section1”). |
host | string | The host and port of the current location (e.g., “example.com:8080”). |
hostname | string | The host name of the current location (e.g., “example.com”). |
href | string | The full URL of the current location. |
origin | string | The origin of the current location (e.g., ”http://example.com:8080”). |
pathname | string | The pathname portion of the current location (e.g., “/products”). |
port | string | The port of the current location (e.g., “8080”). |
protocol | string | The protocol of the current location (e.g., “http:” or “https:”). |
search | string | The 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.