typescriptintermediate
useGeolocation Hook
Accesses browser geolocation API with loading, error states, and watch mode support.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
usePermission Hook
Queries and tracks browser permission state for features like notifications, camera, and geolocation.
Best for: Permission-gated features
#hooks#permissions
typescriptbeginner
usePageVisibility Hook
Detects when the page is hidden or visible using the Page Visibility API.
Best for: Pausing animations
#hooks#visibility
typescriptintermediate
useScreenWakeLock Hook
Prevents the screen from turning off using the Screen Wake Lock API.
Best for: Video playback
#hooks#wake-lock
typescriptintermediate
useFullscreen Hook
Toggle fullscreen mode on an element using the Fullscreen API with state tracking.
Best for: Video players
#hooks#fullscreen