typescriptintermediate

useGeolocation Hook

Accesses browser geolocation API with loading, error states, and watch mode support.

typescript
import { useState, useEffect } from 'react';

interface GeoState {
  latitude: number | null;
  longitude: number | null;
  accuracy: number | null;
  loading: boolean;
  error: string | null;
}

export function useGeolocation(watch = false) {
  const [state, setState] = useState<GeoState>({
    latitude: null, longitude: null, accuracy: null, loading: true, error: null,
  });

  useEffect(() => {
    if (!navigator.geolocation) {
      setState(s => ({ ...s, loading: false, error: 'Geolocation not supported' }));
      return;
    }

    const onSuccess = (pos: GeolocationPosition) => {
      setState({
        latitude: pos.coords.latitude,
        longitude: pos.coords.longitude,
        accuracy: pos.coords.accuracy,
        loading: false,
        error: null,
      });
    };

    const onError = (err: GeolocationPositionError) => {
      setState(s => ({ ...s, loading: false, error: err.message }));
    };

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

  return state;
}

Use Cases

  • Location-based features
  • Map applications

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.