useGeolocation
One of the first custom hooks I wrote was to grab the user’s location using the Geolocation API. I wrote it for a project with two requirements — to get a user’s location on a button press, and to ‘watch’ a user’s location to keep a map preview up to date.
Let’s cut straight to the code:
Usage (Single Location):
Usage (Watch Location):
The hook is super simple to use. The first call returns a position object or an error, the second call will update ‘position’ every time the underlying hook receives an updated position from the Geolocation API, and will maintain an array of all positions observed in ‘locationHistory’.
Get Anthony Humphreys’s stories in your inbox
Join Medium for free to get updates from this writer.
You can check out the code over at GitHub or install it from npm
The design of the underlying hook allows you to seamlessly switch between ‘modes’ too — so you could seamlessly transition between displaying a user’s initial location and showing a user’s journey as they follow directions, for example.
It’s that simple. This is one of the most attractive value propositions offered by hooks — abstracting away logic in an easily reusable and easy to consume manner.
The hook code
This is still something of a work in progress with some incomplete types. (PRs always welcome!)









