Skip to content

useBrowserLocation

Hook that returns reactive browser location state with navigation controls

browser
medium
test coverage
Last changed: 4 days ago

TIP

This hook uses window.location browser api to provide enhanced functionality. Make sure to check for compatibility with different browsers when using this api

Installation

Library
CLI
Manual
typescript
import { useBrowserLocation } from '@siberiacancode/reactuse';

Usage

typescript
const { value, push, back, forward, go } = useBrowserLocation();

Demo

Api

Returns

UseBrowserLocationReturn

Type declaration

typescript
export interface BrowserLocationState {
  /** URL hash including # */
  hash?: string;
  /** URL host */
  host?: string;
  /** URL hostname */
  hostname?: string;
  /** Full URL */
  href?: string;
  /** Number of entries in the session history */
  length?: number;
  /** URL origin */
  origin?: string;
  /** URL pathname */
  pathname?: string;
  /** URL port */
  port?: string;
  /** URL protocol */
  protocol?: string;
  /** URL search string */
  search?: string;
  /** Browser history state */
  state?: unknown;
}

export interface UseBrowserLocationReturn {
  /** Current browser location state */
  value: BrowserLocationState;
  /** Go back in history */
  back: () => void;
  /** Go forward in history */
  forward: () => void;
  /** Move by history delta */
  go: (delta: number) => void;
  /** Navigate to a new URL and push a history entry */
  push: (url: string | URL, state?: unknown, title?: string) => void;
  /** Navigate to a new URL and replace current history entry */
  replace: (url: string | URL, state?: unknown, title?: string) => void;
}

Source

SourceDemo

Contributors

D
debabin
debabin

Released under the MIT License.