-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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>
);
}Returns an object of type UseLocationReturn containing:
-
location(LocationData | null): An object containinglat,lng, andaccuracy(in meters) if permission is granted, otherwisenull. -
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 ifstatusis"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.
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.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM