h3/use's logo

h3/use

Command Palette

Search for a command to run...

useGeolocation

Declarative hook for the browser Geolocation API.

useGeolocation
Declarative Geolocation API hook demo.

Loading...

Installation

Props

PropTypeDefaultDescription
optionsPositionOptions{}Options for getCurrentPosition and watchPosition

Data

PropertyTypeDescription
positionGeolocationPosition | nullThe last known position from the Geolocation API
errorGeolocationPositionError | nullThe last encountered error, if any
isLoadingbooleanWhether the hook is currently loading data
clearWatch() => voidFunction to stop watching position changes

Key Features & Details

  • Declarative interface for both getCurrentPosition and continuous watchPosition.
  • Automatic cleanup on component unmount.
  • Graceful fallback if Geolocation API is not supported.
  • Fully typed with TypeScript.

Browser Support

  • Chrome: Supported (since v5)
  • Firefox: Supported (since v3.5)
  • Safari: Supported (since 5)
  • Edge: Supported
  • Opera: Supported

Security Considerations

  • Requires secure context (HTTPS).
  • User permission prompt is shown on first request.

Best Practices & Caveats

  1. Always handle the error case to inform the user.
  2. Clear the watch when no longer needed to save battery.
  3. Consider asking permission only when necessary.
  4. For frequent updates, throttle or debounce updates to avoid performance issues.
  5. Use maximumAge and timeout options wisely.

Examples

Basic Usage

const { position, error, isLoading } = useGeolocation();
 
if (error) {
  console.error(error);
} else if (isLoading) {
  console.log('Loading position...');
} else if (position) {
  console.log(`Latitude: ${position.coords.latitude}`);
}

Full Example

import React from 'react';
 
import { useGeolocation } from '@/registry/hooks/use-geolocation';
 
export default function LocationDisplay() {
  const { position, error, isLoading, clearWatch } = useGeolocation({
    enableHighAccuracy: true,
    maximumAge: 10000,
    timeout: 5000,
  });
 
  if (error) return <p>Error: {error.message}</p>;
  if (isLoading) return <p>Loading…</p>;
 
  return (
    <div>
      <p>Lat: {position.coords.latitude}</p>
      <p>Lon: {position.coords.longitude}</p>
      <button onClick={clearWatch}>Stop Watching</button>
    </div>
  );
}