DEV Community

Dayanand garg
Dayanand garg

Posted on Edited on

How to track user location in background

React Native Background Location Tracking: What You Actually Need

Correction — 2026: The original version of this article incorrectly suggested that @react-native-community/geolocation and react-native-background-task could reliably send location updates every 15 minutes, including when the screen was locked.

That implementation was incomplete. It included an unused dependency, unsupported configuration options, and insufficient background-execution handling. I've revised this article to explain the limitations and provide a safer starting point.

Understanding background location tracking

There are three different scenarios:

  1. Foreground: The app is visible and actively running.
  2. Background: The user switches apps or locks the screen.
  3. Terminated: The app's process is no longer running.

These scenarios have different operating-system restrictions. A JavaScript location watcher cannot guarantee tracking across all three.

1. Install the package

npm install @react-native-community/geolocation
Enter fullscreen mode Exit fullscreen mode

The original article also installed react-native-background-task, but never registered or executed a background task. That dependency is unnecessary for the following example.

2. Configure foreground permissions

Android — AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Enter fullscreen mode Exit fullscreen mode

Android 6+ also requires runtime permission requests. On Android 12+, request coarse and fine permissions together so users can choose approximate or precise location.

iOS — Info.plist

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is needed while you use the tracking feature.</string>
Enter fullscreen mode Exit fullscreen mode

This example requests foreground location access only. Don't request background access unless your app actually implements and needs background tracking.

3. Watch location in the foreground

The following is an illustrative React Native component using documented Geolocation APIs.

import {useEffect} from 'react';
import {PermissionsAndroid, Platform} from 'react-native';
import Geolocation from '@react-native-community/geolocation';

Geolocation.setRNConfiguration({
  skipPermissionRequests: false,
  authorizationLevel: 'whenInUse',
});

async function requestLocationPermission() {
  if (Platform.OS !== 'android') {
    return {granted: true, precise: true};
  }

  const {ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION} =
    PermissionsAndroid.PERMISSIONS;

  const results = await PermissionsAndroid.requestMultiple([
    ACCESS_COARSE_LOCATION,
    ACCESS_FINE_LOCATION,
  ]);

  const precise =
    results[ACCESS_FINE_LOCATION] ===
    PermissionsAndroid.RESULTS.GRANTED;

  const approximate =
    results[ACCESS_COARSE_LOCATION] ===
    PermissionsAndroid.RESULTS.GRANTED;

  return {granted: precise || approximate, precise};
}

export default function LocationTracker() {
  useEffect(() => {
    let active = true;
    let watchId;

    async function startTracking() {
      try {
        const permission = await requestLocationPermission();

        if (!active || !permission.granted) return;

        watchId = Geolocation.watchPosition(
          position => {
            if (!active) return;

            console.log('Location:', position.coords);
          },
          error => {
            console.warn('Location error:', error.message);
          },
          {
            enableHighAccuracy: permission.precise,
            distanceFilter: 10,
            interval: 60000,
            fastestInterval: 30000,
          },
        );
      } catch (error) {
        console.warn('Unable to start tracking:', error);
      }
    }

    startTracking();

    return () => {
      active = false;
      if (watchId != null) {
        Geolocation.clearWatch(watchId);
      }
    };
  }, []);

  return null;
}
Enter fullscreen mode Exit fullscreen mode

Mount this component only while the user has enabled the tracking feature. Unmounting it removes its location watcher.

Important limitations:

  • interval and fastestInterval are Android-specific preferences, not exact timers.
  • distanceFilter controls movement-based filtering, not periodic scheduling.
  • iOS handles location delivery according to its own policies.
  • This example is intended for foreground use. It does not implement reliable background execution, terminated-app recovery, or uploading locations to a server.

4. What reliable background tracking requires

Android

For continuous tracking after the user backgrounds the app, Android generally requires a properly implemented location foreground service.

That involves:

  • Declaring the appropriate foreground-service permissions and service type, including FOREGROUND_SERVICE_LOCATION when applicable.
  • Starting the service under Android's execution restrictions.
  • Showing the required user-visible notification.
  • Requesting ACCESS_BACKGROUND_LOCATION separately when the use case requires it.
  • Handling interruptions and operating-system battery restrictions.

Adding a foregroundService object inside Geolocation.watchPosition() does not create an Android foreground service.

iOS

iOS requires appropriate Core Location configuration, authorization, and the Location updates background capability.

Depending on the use case, implementation may involve standard location updates, significant-location-change monitoring, or region monitoring.

Merely adding UIBackgroundModes to Info.plist does not make JavaScript run indefinitely in the background.

5. Can we upload location every 15 minutes?

Not reliably using the original implementation.

Neither Android nor iOS guarantees that a location callback or background task will execute at an exact 15-minute interval under all conditions.

For an application requiring periodic server updates, you must design around delayed or missing updates, offline storage, retries, permission revocation, and process termination.

Collect and transmit location only with clear user consent, and use an authenticated, secure API.

6. What about geofencing?

Geofencing is a different requirement.

If your goal is to detect when someone enters or exits one of five locations, consider Android's Geofencing API or iOS Core Location region monitoring, typically through a dedicated React Native integration.

Polling GPS every few minutes is not necessary for many geofencing use cases. Geofence events also aren't guaranteed to arrive instantaneously.

Final takeaway

@react-native-community/geolocation is useful for obtaining and observing device location, but a location watcher is not a complete background-tracking architecture.

For production background tracking, implement the required native execution mechanisms, follow platform permission policies, and test on real devices.

This article is a correction and architectural starting point, not a production-tested background-tracking implementation.

References

Top comments (4)

Collapse
 
ngvsang profile image
Nguyễn Viết Sáng •

Hi, I don't see you use react-native-background-task, so what does it help?

Collapse
 
eduardovargasleffa profile image
Eduardo Vargas Leffa •

and not worked for me

Collapse
 
ofryl profile image
Collapse
 
jasim678 profile image
Jasim Khan •

how to add geofence in this background running code i have 5 location i want make notification on entry and exit how can i achieve this