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:
| Parameter | Type | Default | Description |
|---|---|---|---|
enableHighAccuracy | boolean | false | Requests the most accurate location possible (may consume more power). |
maximumAge | number | 0 | Maximum age (in milliseconds) of a cached position before a fresh one is requested. |
timeout | number | 10000 | Maximum time (in milliseconds) to wait for a position. |
retryLimit | number | 3 | Maximum number of retry attempts when location retrieval fails. |
retryDelay | number | 2000 | Delay (in milliseconds) between retry attempts. |
Return Value
useGeoLocation returns an object containing:
| Property | Type | Description |
|---|---|---|
loading | boolean | true while a position is being fetched, otherwise false. |
error | { code: number; message: string } | null | Error details if location retrieval fails, otherwise null. |
coords | GeolocationCoordinates | null | The latest coordinates (latitude, longitude, accuracy, etc.), or null before the first fix. |
Behavior
- Subscribes to location updates via
navigator.geolocation.watchPositionand exposes the latest coordinates. - On error, automatically retries up to
retryLimittimes, waitingretryDelaymilliseconds 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.