Skip to content

useLocation

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useLocation

Securely accesses the browser's Geolocation API to retrieve the user's current GPS coordinates. It gracefully handles browser permission states, safely accounts for missing hardware, and provides a built-in retry mechanism for user-driven permission flows.

Usage Examples

Basic

A standard implementation requesting the user's location and rendering the coordinates.

import { useLocation } from "react-hook-lab";

function MapView() {
  const { location, status, error, retry } = useLocation();

  if (status === "prompting") return <p>Please allow location access...</p>;
  if (status === "denied" || error) return (
    <div>
      <p>Error: {error}</p>
      <button onClick={retry}>Retry</button>
    </div>
  );

  if (!location) return null;

  return (
    <div>
      <p>Latitude: {location.lat}</p>
      <p>Longitude: {location.lng}</p>
      <p>Accuracy: Within {location.accuracy} meters</p>
    </div>
  );
}

API Reference

Returns

Returns an object of type UseLocationReturn containing:

  • location (LocationData | null): An object containing lat, lng, and accuracy (in meters) if permission is granted, otherwise null.
  • status (LocationStatus): The current state of the request.
    • "idle": Initialization state.
    • "prompting": The browser is currently asking the user for permission.
    • "granted": Location was successfully retrieved.
    • "denied": The user blocked the request.
    • "error": An unexpected hardware or network error occurred.
    • "unsupported": The Geolocation API does not exist on this device.
  • error (string | null): A human-readable error string if status is "error", "denied", or "unsupported".
  • retry (() => void): A function to re-trigger the location request. Note: If the user permanently denied permission, this will instantly fail unless they manually change their browser settings.

Core Working

When initialized, useLocation first queries the navigator.permissions API (if available) to detect if the user has already granted or denied access without triggering an invasive popup.

If the status is "prompt", it calls navigator.geolocation.getCurrentPosition() requesting high accuracy (enableHighAccuracy: true) with a 10-second timeout. Crucially, it attaches an event listener to the navigator.permissions object so that if the user manually revokes or grants location permissions in their browser's URL bar settings while the app is running, the hook automatically detects the change and resyncs the React state in real-time.

Clone this wiki locally