Skip to Content
HooksuseGeolocation

useGeolocation

useGeolocation reads the browser Geolocation API and keeps the latest coordinates in React state.

Live Example

Permission-driven location lookup

This demo requests location only when you click the button, which is safer for docs and closer to real product usage.

Browser location

Geolocation lookup

Idle

This demo does not request location on page load. Click the button to ask for browser permission and fetch the current coordinates.

Geolocation is not supported.

This browser environment does not expose the Geolocation API.

Import

import { useGeolocation } from "react-rsc-kit/client";

Signature

const geolocation = useGeolocation(options?, callback?, isEnabled?);

Parameters

NameTypeDefaultDescription
options{ enableHighAccuracy?: boolean; maximumAge?: number; timeout?: number; watch?: boolean; requestOnMount?: boolean }{}Browser geolocation options plus hook behavior flags.
callback(coordinates) => voidundefinedRuns whenever coordinates update successfully.
isEnabledbooleantrueEnables or disables geolocation watching.

Returns

KeyDescription
accuracy, altitude, altitudeAccuracy, heading, latitude, longitude, speed, timestampLatest location fields.
errorLast GeolocationPositionError, if one exists.
loadingWhether a geolocation request is in progress.
permissionStatePermission state from the Permissions API when available.
isSupportedWhether geolocation exists in the current environment.
isEnabledWhether the hook is currently enabled.
isWatchingWhether a watch subscription is active.
getCurrentPositionRuns a manual one-time location lookup.
cancelClears the active watch subscription.

Usage

"use client"; import { useGeolocation } from "react-rsc-kit/client"; export function LocationReadout() { const { latitude, longitude, loading, error, getCurrentPosition } = useGeolocation( { enableHighAccuracy: true, watch: false, requestOnMount: false, maximumAge: 15000, timeout: 12000, }, (nextCoordinates) => { console.log("updated:", nextCoordinates.latitude, nextCoordinates.longitude); }, ); return ( <div> <button type="button" onClick={getCurrentPosition}> Get location </button> {loading ? <p>Locating...</p> : null} {error ? <p>Unable to read location.</p> : null} {latitude !== null && longitude !== null ? ( <p> {latitude}, {longitude} </p> ) : null} </div> ); }

Notes

  • This hook is client-only and depends on browser permission.
  • watch defaults to true and requestOnMount defaults to true to preserve the original behavior.
  • getCurrentPosition is useful when you want permission to be user-triggered instead of automatic.
Last updated on