UseGeolocation
guarahooks/use-geolocationFreeHook
Declarative wrapper for the Geolocation API.
Live preview
live · rendered by the registry
Rendered by guarahooks on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://guarahooks.com/r/use-geolocation.jsonSource
1'use client';23import { useCallback, useEffect, useRef, useState } from 'react';45export interface GeolocationState {6 position: GeolocationPosition | null;7 error: GeolocationPositionError | null;8 isLoading: boolean;9 clearWatch: () => void;10}1112export function useGeolocation(options?: PositionOptions): GeolocationState {13 const [position, setPosition] = useState<GeolocationPosition | null>(null);14 const [error, setError] = useState<GeolocationPositionError | null>(null);15 const [isLoading, setIsLoading] = useState<boolean>(true);1617 const watchId = useRef<number | null>(null);1819 const clearWatch = useCallback(() => {20 if (watchId.current !== null && 'geolocation' in navigator) {21 navigator.geolocation.clearWatch(watchId.current);22 watchId.current = null;23 }24 }, []);2526 useEffect(() => {27 if (!('geolocation' in navigator)) {28 setError({29 code: 0,30 message: 'Geolocation API not supported',31 } as GeolocationPositionError);32 setIsLoading(false);33 return;34 }3536 const onSuccess = (pos: GeolocationPosition) => {37 setPosition(pos);38 setError(null);39 setIsLoading(false);40 };4142 const onError = (err: GeolocationPositionError) => {43 setError(err);44 setPosition(null);45 setIsLoading(false);46 };4748 navigator.geolocation.getCurrentPosition(onSuccess, onError, options);4950 const id = navigator.geolocation.watchPosition(onSuccess, onError, options);51 watchId.current = id;5253 return () => {54 clearWatch();55 };56 }, [options, clearWatch]);5758 return { position, error, isLoading, clearWatch };59}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
