useGeolocation
Tracks the user's geographic location using the Geolocation API.
About
A hook to provide the geolocation info on client side.
Examples
Getting geolocation in a component
import { useGeolocation } from "rooks";
import React from "react";
import { useState } from "react";
function App() {
const geoObj = useGeolocation();
return (
<div
className="App"
style={{
display: "flex",
alignItems: "center",
flexDirection: "column",
}}
>
<h1>Rooks : useGeolocation Example</h1>
<p>{geoObj && JSON.stringify(geoObj)}</p>
</div>
);
}
export default App;Getting geolocation in a component on some condition
import { useGeolocation } from "rooks";
import React from "react";
import { useState } from "react";
export default function App() {
const [when, setWhen] = React.useState(false);
const geoObj = useGeolocation({
when,
});
return (
<div
className="App"
style={{
display: "flex",
alignItems: "center",
flexDirection: "column",
}}
>
<h1>Rooks : useGeolocation Example</h1>
<p>Check out console</p>
<div
style={{
display: "flex",
alignItems: "center",
flexDirection: "column",
}}
>
<button
onClick={() => {
setWhen(true);
}}
>
Get Geolocation
</button>
<p>{geoObj && JSON.stringify(geoObj)}</p>
</div>
</div>
);
}Parameters
The argument is an object with the following optional items:
| Option | Type | Default | Description |
|---|---|---|---|
enableHighAccuracy | boolean | false | Ask for a more accurate fix, potentially using more power. |
timeout | number | Infinity | Maximum wait in milliseconds. |
maximumAge | number | 0 | Oldest cached position accepted, in milliseconds. |
when | boolean | true | Request a position only while true. |
Return value
Returns null before a request finishes. A successful or failed request then returns:
{
lat?: number;
lng?: number;
isError: boolean;
message: string;
}Behavior and lifecycle
This is a one-shot getCurrentPosition request, not continuous tracking. It runs again when when or a position option changes. Setting when to false does not clear the last result. The platform request cannot be cancelled, but a late result is ignored after unmount. Permission denials and unsupported browsers resolve as { isError: true, message } rather than throwing.
Compatibility and accessibility
The request begins in an effect, so SSR returns null. Geolocation generally requires HTTPS and user permission. Explain why location is needed, request it in context, provide manual alternatives, and treat coordinates as sensitive approximate data rather than proof of identity or presence.