BrowserBeginnerSSR-safehooks/browser/useGeolocation.ts

useGeolocation

Geolocation wrapper.

Import

TypeScript
import { useGeolocation } from '@/hooks';

API

Signature

useGeolocation(options?) → state & { refresh }

When to use

Use useGeolocation instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Returns defaults on the server; hydrates on the client.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useGeolocation
Editor
function MapPin() {
  const { latitude, longitude, loading, error, refresh } = useGeolocation({
    enabled: true,
  });
  if (loading) return <p>Locating…</p>;
  if (error) return <p>{error.message}</p>;
  return (
    <button onClick={refresh}>
      {latitude}, {longitude}
    </button>
  );
}
Preview

Implementation source

Full library source for useGeolocation — copy into your project when you are not installing a package yet.

hooks/browser/useGeolocation.ts
import { useCallback, useEffect, useState } from 'react';
import { hasNavigator, isBrowser } from '../utility/isBrowser';

export interface GeolocationState {
  loading: boolean;
  accuracy: number | null;
  altitude: number | null;
  altitudeAccuracy: number | null;
  heading: number | null;
  latitude: number | null;
  longitude: number | null;
  speed: number | null;
  timestamp: number | null;
  error: GeolocationPositionError | Error | null;
}

export interface UseGeolocationOptions extends PositionOptions {
  /** @default true */
  enabled?: boolean;
  watch?: boolean;
}

const initial: GeolocationState = {
  loading: false,
  accuracy: null,
  altitude: null,
  altitudeAccuracy: null,
  heading: null,
  latitude: null,
  longitude: null,
  speed: null,
  timestamp: null,
  error: null,
};

/** SSR-safe geolocation wrapper. */
export function useGeolocation(
  options: UseGeolocationOptions = {},
): GeolocationState & { refresh: () => void } {
  const { enabled = true, watch = false, ...positionOptions } = options;
  const [state, setState] = useState<GeolocationState>(initial);

  const onSuccess = useCallback((pos: GeolocationPosition) => {
    setState({
      loading: false,
      accuracy: pos.coords.accuracy,
      altitude: pos.coords.altitude,
      altitudeAccuracy: pos.coords.altitudeAccuracy,
      heading: pos.coords.heading,
      latitude: pos.coords.latitude,
      longitude: pos.coords.longitude,
      speed: pos.coords.speed,
      timestamp: pos.timestamp,
      error: null,
    });
  }, []);

  const onError = useCallback((error: GeolocationPositionError) => {
    setState((prev) => ({ ...prev, loading: false, error }));
  }, []);

  const refresh = useCallback(() => {
    if (!isBrowser() || !hasNavigator() || !navigator.geolocation) {
      setState((prev) => ({
        ...prev,
        loading: false,
        error: new Error('Geolocation is not available'),
      }));
      return;
    }
    setState((prev) => ({ ...prev, loading: true }));
    navigator.geolocation.getCurrentPosition(onSuccess, onError, positionOptions);
  }, [onSuccess, onError, positionOptions]);

  useEffect(() => {
    if (!enabled || !isBrowser() || !hasNavigator() || !navigator.geolocation) {
      return;
    }

    setState((prev) => ({ ...prev, loading: true }));

    if (watch) {
      const id = navigator.geolocation.watchPosition(
        onSuccess,
        onError,
        positionOptions,
      );
      return () => navigator.geolocation.clearWatch(id);
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError, positionOptions);
  }, [enabled, watch, onSuccess, onError]); // positionOptions intentionally shallow

  return { ...state, refresh };
}

Copy-paste example

useGeolocation.example.tsx
'use client';

import { useGeolocation } from '@/hooks';

export function MapPin() {
  const { latitude, longitude, loading, error, refresh } = useGeolocation({
    enabled: true,
  });
  if (loading) return <p>Locating…</p>;
  if (error) return <p>{error.message}</p>;
  return (
    <button onClick={refresh}>
      {latitude}, {longitude}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
  • Source of truth: open hooks/browser/useGeolocation.ts for implementation details