Skip to main content

useGeoLocation

useGeoLocation is a custom hook that tracks the user's geolocation in real time using navigator.geolocation.watchPosition, with automatic retries on failure.

Usage

import { useGeoLocation } from "hookify-react";

export default function GeoLocationExample() {
const { loading, error, coords } = useGeoLocation({ enableHighAccuracy: true });

if (loading) return <p>Fetching location...</p>;
if (error) return <p>Error: {error.message}</p>;

return (
<p>
Latitude: {coords?.latitude}, Longitude: {coords?.longitude}
</p>
);
}

API Reference

Parameters

useGeoLocation accepts a single optional options object. Each property is optional:

ParameterTypeDefaultDescription
enableHighAccuracybooleanfalseRequests the most accurate location possible (may consume more power).
maximumAgenumber0Maximum age (in milliseconds) of a cached position before a fresh one is requested.
timeoutnumber10000Maximum time (in milliseconds) to wait for a position.
retryLimitnumber3Maximum number of retry attempts when location retrieval fails.
retryDelaynumber2000Delay (in milliseconds) between retry attempts.

Return Value

useGeoLocation returns an object containing:

PropertyTypeDescription
loadingbooleantrue while a position is being fetched, otherwise false.
error{ code: number; message: string } | nullError details if location retrieval fails, otherwise null.
coordsGeolocationCoordinates | nullThe latest coordinates (latitude, longitude, accuracy, etc.), or null before the first fix.

Behavior

  • Subscribes to location updates via navigator.geolocation.watchPosition and exposes the latest coordinates.
  • On error, automatically retries up to retryLimit times, waiting retryDelay milliseconds between attempts; on a successful fix the retry counter is reset.
  • Options are consumed by their primitive values (not by object identity), so passing a fresh inline {} options object on every render does not cause an infinite re-subscription loop.
  • Cleans up the active watcher and any pending retry timer when the component unmounts.
  • Guards against missing navigator.geolocation: if geolocation is unsupported, it sets an error (code: 0) and stops loading instead of throwing.