What is a Custom Hook?
Custom hooks in React offer a convenient way to encapsulate and reuse logic across components. By creating a custom hook for geolocation, we can abstract away the complexity of accessing and managing location data, resulting in cleaner and more maintainable code.
Introducing Our Geolocation Custom Hook
Geolocation is a powerful feature that enables web applications to access a user's geographical location. Whether you're building a weather app, a food delivery service, or a travel planner, integrating geolocation can enhance user experiences and provide personalized content.
Developing the Custom Geolocation Hook
Let's dive into the implementation of our custom geolocation hook. We'll call it useGeoLocation
.
import React,{useState,useEffect} from 'react'
const useGeoLocation = () => {
const [location,setLocation] = useState({
loading:false,
coordinates:{latitude:'',longitude:''}
});
//onSuccess
const onSuccess = (location) => {
setLocation({
loading:true,
coordinates:{
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}
})
}
//onError
const onError = (error) => {
setLocation({
loading:true,
error
})
}
useEffect(() => {
if(!('geolocation' in navigator)){
onError({
code:0,
message:'Geolocation not supported'
})
}
navigator.geolocation.getCurrentPosition(onSuccess,onError);
}, [])
return location;
}
export default useGeoLocation
Using the Custom Hook
import React from 'react';
import {useGeoLocation} from 'geo-location-hook';
const MyComponent = () => {
const { loading, coordinates, error } = useGeoLocation();
if (!loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
Latitude: {coordinates.latitude}, Longitude: {coordinates.longitude}
</div>
);
};
export default MyComponent;
Thanks a lot for reading till the end ๐ If you liked the article, please give likes and share it with your others.
Email: atul19251@gmail.com
LinkedIn: https://www.linkedin.com/in/atul-kumar-singh-673357102/