watchPositionAsync
- React Native course
- Advanced
- Lesson 22/83
- 5 min
Learn location tracking with watchPositionAsync.
watchPositionAsync
To continuously track the location as the user moves you use Location.watchPositionAsync. This function returns a subscription; on each location change a callback is called. When the component unmounts the subscription is removed with subscription.remove().
The function takes two parameters: an options object and a callback. Example: const sub = await Location.watchPositionAsync({ accuracy: Location.Accuracy.High }, (loc) => console.log(loc.coords)). The subscription is assigned to a variable; cleanup is done in the return of useEffect. This pattern keeps the user's marker live on map apps.
useEffect and cleanup
You set up continuous location tracking inside useEffect. This hook is called once when the component mounts. You set up the subscription inside it and return a cleanup function. The cleanup function removes the subscription when the component unmounts; this stops the location updates.
Example pattern: useEffect(() => {{ (async () => {{ const sub = await Location.watchPositionAsync(...); subscriptionRef.current = sub; }})(); return () => subscriptionRef.current?.remove(); }}, []). The empty dependency array [] ensures the hook is called only once. You keep the subscription in a ref because it is created inside an async function.
Practice Track location continuously
Complete the empty useEffect. Call const sub = await Location.watchPositionAsync({ accuracy: Location.Accuracy.High }, (loc) => console.log(loc.coords)). Clean up with return () => sub.remove(). The second argument of useEffect should be [].
Starter code
import React from 'react';
import * as Location from 'expo-location';
export function useWatchLocation() {
React.useEffect(() => {
let sub;
// track location continuously and return cleanup
}, []);
}Sample solution
let sub;
(async () => {
sub = await Location.watchPositionAsync(
{ accuracy: Location.Accuracy.High },
(loc) => console.log(loc.coords)
);
})();
return () => sub && sub.remove();Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the subscription variable
const ____ = await Location.watchPositionAsync(options, callback);
const subscription = await Location.watchPositionAsync(options, callback);
Explanation: The subscription variable carries the subscription.
2 Match each part to its role
| Term | Meaning |
|---|---|
watchPositionAsync |
Tracks continuously |
subscription.remove() |
Removes the subscription |
useEffect |
Setup place |
accuracy |
Accuracy option |
3 What is done when the component unmounts?
return () => { ??? }- Open a new subscription
- Wait for a location update
- Remove the subscription with remove() Correct answer
- Throw an error
Explanation: When the component unmounts, the subscription is removed with remove().