Software Crafting

Reliable Background Processing in React Native: Architecting Headless JS and WorkManager for Offline Data Sync

BBadal SinghMobile Development13 min read04 Apr 2026Updated 2026-10-27
A translucent smartphone lying at an angle on a dark background, its screen showing glowing cyan and purple gears over streams of code, surrounded by a faint network of connected dots

TL;DR: JavaScript timers stop when a React Native app is backgrounded, so offline sync has to be driven by the operating system's schedulers: WorkManager on Android and BGTaskScheduler on iOS. Neither gives you a fixed schedule; both decide when to run your work and both can stop it early. For most apps the right move is a maintained library (expo-background-task or react-native-background-fetch) that wires those schedulers to a JavaScript task, combined with a persistent, idempotent SQLite queue that survives being cut off mid-run. This guide explains the platform rules, shows the library setup, explains what a correct hand-rolled bridge has to do, and builds the queue.

Key Takeaways

  • On iOS, applicationDidEnterBackground has about five seconds to return before the app is suspended. beginBackgroundTask can extend that briefly, but the amount of time is decided by the system and exposed through backgroundTimeRemaining; it is not a scheduling mechanism.
  • BGTaskScheduler runs tasks when the system decides. earliestBeginDate is only a lower bound, and BGProcessingTask runs only while the device is idle and is terminated when the user starts using the device.
  • WorkManager is the recommended Android API for deferrable, persistent work. A worker only gets retries and backoff if it reports the real outcome, so the worker must wait for the JavaScript task to finish before returning.
  • Calling startService() while the app is in the background is not allowed on Android 8.0+ for apps targeting API 26+, which is why a worker that only fires an intent at a HeadlessJsTaskService is fragile.
  • Headless JS does not retry by default. Retries require a HeadlessJsRetryPolicy on the native side and throwing HeadlessJsTaskError from JavaScript.
  • Prefer a maintained library over hand-rolled native glue, especially on React Native 0.76+ where the New Architecture is enabled by default.
  • Store pending mutations in SQLite, not AsyncStorage, send them in order with an idempotency key, and delete a row only after the server confirms it.

Why Background Sync Fails in React Native

A typical offline-first app lets users create records, edit forms and complete workflows without a connection, and stores those mutations in a local queue. The failure report usually reads like this:

"I filled out the inspection report, but my manager never saw it."

The data was saved locally but never sent. The user switched apps or locked the phone before connectivity returned, and the operating system stopped running the app's JavaScript.

That is expected behavior, not a bug. Both platforms aggressively limit background execution to protect battery life:

  • iOS suspends a backgrounded app shortly after applicationDidEnterBackground returns. Apple documents that this delegate method has five seconds to do its work and return, after which the system suspends the app.
  • Android applies Doze, App Standby Buckets and background execution limits. Since Android 8.0 the system does not allow a background app to create a background service, and an idle app's background services are stopped.

A setInterval loop, an AppState listener or a pending promise does nothing once the JavaScript thread is suspended. To sync later, you have to ask the operating system to wake the app and give it a bounded window of time, then run your sync code in that window.

The Platform Primitives and What They Actually Guarantee

Before choosing a library or writing native code, it helps to be exact about what each API promises. Most broken background sync implementations assume guarantees that the platform never made.

PlatformAPIWhen it runsHow long it can runGood fit
iOSbeginBackgroundTaskImmediately, while the app is moving to the backgroundA limited, system-decided window; read backgroundTimeRemainingFinishing an upload that already started
iOSBGAppRefreshTask (via BGTaskScheduler)When the system decides, based on usage, battery and networkShort; meant for small content refreshesPulling a small delta, flushing a few rows
iOSBGProcessingTask (via BGTaskScheduler)Only when the device is idle; stopped when the user starts using the deviceCan run for minutes, but can be interruptedLarge queue flushes, database maintenance
iOSBackground URLSessionTransfers continue out of process after the app is suspendedManaged by the systemLarge file uploads and downloads
AndroidWorkManager OneTimeWorkRequestAs soon as constraints (for example network) are met, subject to DozeBounded; long work should use setForeground with a foreground serviceFlushing the queue after a local write
AndroidWorkManager PeriodicWorkRequestRepeating, with a minimum interval of 15 minutesSame as aboveSafety-net sync that catches missed flushes
AndroidForeground serviceImmediately, with a user-visible notificationLong-running; Android 14+ requires a declared foreground service typeWork the user is actively waiting on

Two consequences matter for the design:

  1. There is no precise schedule on either platform. Apple states that earliestBeginDate only guarantees the task will not begin sooner, not that it starts at that time. The Expo docs for expo-background-task note that iOS often ignores short intervals and may run tasks in windows such as overnight.
  2. Every run can be cut off. Your sync code must assume it may be stopped after any statement, and the next run must be able to resume.

Production Note: Do not start a long sync from an AppState change to background. On iOS you have a few seconds in applicationDidEnterBackground, and even with beginBackgroundTask the extra time is limited and not guaranteed. A request that is still in flight when the app suspends may or may not complete, so the queue must treat its outcome as unknown and retry safely.

Choosing an Approach: Library vs Hand-Rolled Native Code

There are two realistic paths. A maintained library that already connects WorkManager and BGTaskScheduler to a JavaScript task, or your own native modules on both platforms.

Concernexpo-background-taskreact-native-background-fetchHand-rolled WorkManager + BGTaskScheduler
Android schedulerWorkManagerNative library maintained by Transistor SoftwareWhatever you write
iOS schedulerBGTaskScheduler (processing task)Background fetch plus scheduleTask for custom tasksWhatever you write
Runs after app is terminatedNo; tasks stop when the user kills the app, resume on launchAndroid yes with enableHeadless and stopOnTerminate: false; iOS noAndroid possible; iOS no once the user force quits
Minimum interval15 minutes (minimumInterval in minutes)About 15 minutes for fetch events, throttled by the OS15 minutes for periodic WorkManager work
New Architecture (RN 0.76+)Expo module; requires expo installed in bare appsShips a codegen spec (TurboModule)You own the migration and every future RN upgrade
Custom constraints and policiesLimitedSome (requiredNetworkType, periodic or one-shot tasks)Full control over constraints, backoff, foreground info
Maintenance costLowLowHigh: two native codebases tied to React Native internals

For most product teams, start with a library. Hand-roll only when you have a concrete requirement a library cannot meet, such as custom WorkManager constraints, chained work, or a foreground worker with a specific notification.

Option A: expo-background-task

expo-background-task uses WorkManager on Android and BGTaskScheduler on iOS, and runs your JavaScript through expo-task-manager. It works in Expo projects and in bare React Native apps once expo is installed. The snippets below follow the documented API for expo-background-task and expo-task-manager 58.x.

Install it:

npx expo install expo-background-task expo-task-manager

On iOS the app needs processing in UIBackgroundModes and com.expo.modules.backgroundtask.processing in BGTaskSchedulerPermittedIdentifiers. With Continuous Native Generation, npx expo prebuild adds both. In a bare project, add them to Info.plist yourself:

<key>UIBackgroundModes</key>
<array>
    <string>processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.expo.modules.backgroundtask.processing</string>
</array>

Define the task at module scope, in a file imported from your entry point, so it is registered whenever the JavaScript runtime starts, including a background launch:

// backgroundSync.ts
import * as BackgroundTask from 'expo-background-task';
import * as TaskManager from 'expo-task-manager';
import { processSyncQueue } from './database/sync';

export const SYNC_TASK = 'offline-sync';

TaskManager.defineTask(SYNC_TASK, async () => {
  try {
    await processSyncQueue({ budgetMs: 25_000 });
    return BackgroundTask.BackgroundTaskResult.Success;
  } catch (error) {
    console.error('[BackgroundSync] failed', error);
    return BackgroundTask.BackgroundTaskResult.Failed;
  }
});

export async function registerSyncTask() {
  const status = await BackgroundTask.getStatusAsync();
  if (status === BackgroundTask.BackgroundTaskStatus.Restricted) {
    console.warn('[BackgroundSync] background tasks are restricted on this device');
    return;
  }
  await BackgroundTask.registerTaskAsync(SYNC_TASK, { minimumInterval: 15 });
}

Key decisions in this code:

  • defineTask runs at import time, not inside a component. When the OS launches the app in the background, no screens mount, so a task defined in a useEffect would never be registered.
  • minimumInterval is in minutes and 15 is the documented minimum. The default is 12 hours. It is a lower bound, not a schedule.
  • getStatusAsync lets you detect Restricted (for example when the user disabled Background App Refresh) and show an in-app hint instead of failing silently.
  • processSyncQueue receives a time budget so it stops starting new work well before the OS would stop it. The queue section below shows how that works.

On iOS you can also call BackgroundTask.addExpirationListener to clean up when the system ends a task early. During development, BackgroundTask.triggerTaskWorkerForTestingAsync() runs the task on demand in debug builds. The Background Tasks API is not supported in the iOS simulator, so test on a physical device.

One limitation to plan around: all JavaScript tasks registered with expo-background-task share one worker, and the last registered task sets the minimum interval.

Option B: react-native-background-fetch

react-native-background-fetch (version 4.x at the time of writing) has been maintained for years and exposes more control on Android, including headless execution after the app is terminated. Its API centres on configure, an event callback, a timeout callback and a mandatory finish(taskId):

// backgroundFetch.ts
import BackgroundFetch from 'react-native-background-fetch';
import { processSyncQueue } from './database/sync';

export async function initBackgroundFetch() {
  await BackgroundFetch.configure(
    {
      minimumFetchInterval: 15, // minutes; the OS may run it less often
      stopOnTerminate: false, // Android: keep running after the app is terminated
      startOnBoot: true, // Android: requires stopOnTerminate: false
      enableHeadless: true, // Android: requires stopOnTerminate: false
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_ANY,
    },
    async (taskId) => {
      try {
        await processSyncQueue({ budgetMs: 25_000 });
      } finally {
        BackgroundFetch.finish(taskId);
      }
    },
    (taskId) => {
      // The OS is about to end our background time.
      BackgroundFetch.finish(taskId);
    },
  );
}

For Android headless runs, register a headless handler at module scope in index.js:

// index.js (module scope, next to AppRegistry.registerComponent)
import BackgroundFetch from 'react-native-background-fetch';
import { processSyncQueue } from './src/database/sync';

BackgroundFetch.registerHeadlessTask(async ({ taskId, timeout }) => {
  if (timeout) {
    BackgroundFetch.finish(taskId);
    return;
  }
  try {
    await processSyncQueue({ budgetMs: 25_000 });
  } finally {
    BackgroundFetch.finish(taskId);
  }
});

Always call finish(taskId), including in the timeout callback; the library warns at runtime if no timeout callback is provided, because that callback is the OS signal that background time is about to expire. The library's own README notes that iOS stops delivering events once the app is terminated, so stopOnTerminate: false only applies to Android. Follow the library's setup guide for the iOS Info.plist entries, because they depend on whether you use only fetch events or also scheduleTask.

Option C: What a Correct Hand-Rolled Bridge Requires

Older guides (including an earlier version of this article) show a WorkManager Worker that calls context.startService() on a HeadlessJsTaskService and immediately returns Result.success(). That pattern has two real problems:

  1. The worker reports success before any JavaScript runs. WorkManager only applies backoff and retry when the worker returns Result.retry(). A JavaScript error thrown later never reaches WorkManager, so failed syncs are silently treated as successful.
  2. Starting a service from the background is restricted. Android 8.0 does not allow a background app to create a background service. In practice the call throws IllegalStateException when the app is not in an allowed state. The React Native Headless JS docs now start the service with startForegroundService(), which in turn requires calling startForeground() with a notification within five seconds.

If you need to hand-roll, the requirements are:

  • Use a CoroutineWorker (Kotlin) or ListenableWorker (Java) so doWork() can suspend until the JavaScript task reports a result, then return Result.success(), Result.retry() or Result.failure() accordingly. CoroutineWorker cancels its coroutine automatically when WorkManager stops the work, so propagate that cancellation to the JavaScript side.
  • Start the JavaScript task without a background service. Get the current React context from the app's React host and start the task through React Native's headless task context, rather than starting a Service from the worker. These internals differ between the legacy architecture and the New Architecture, which is default since React Native 0.76, so pin and test the exact React Native version you target.
  • Report completion from JavaScript explicitly. A small native module with complete(taskId, ok) is the simplest contract. Do not infer success from "the task finished".
  • For work longer than a few minutes, call setForeground() with ForegroundInfo. If you target Android 14 (API 34) or higher, Android requires a foreground service type for long-running workers, declared on WorkManager's SystemForegroundService in the manifest.
  • On iOS, call setTaskCompletedWithSuccess: exactly once per BGTask, from both the completion path and the expirationHandler, and submit the next request with submitTaskRequest:error:. Do not build a new RCTBridge per task; on the New Architecture the bridge APIs are replaced by the React host, and older snippets that call enqueueJSCall were written for the legacy architecture.

This is a meaningful amount of native code to own across every React Native upgrade, which is why the library options above are the default recommendation.

If you do use plain Headless JS on Android, note that it does not retry on its own. Retries require passing a HeadlessJsRetryPolicy such as LinearCountingRetryPolicy in the HeadlessJsTaskConfig and throwing HeadlessJsTaskError from JavaScript. Also note that by default a Headless JS task crashes the app if it runs while the app is in the foreground, unless the fourth allowedInForeground argument is true.

Architecting the Persistent Offline Queue

The scheduler only decides when your code runs. Whether data arrives intact depends on the queue. Background runs can stop at any moment, so every step must be safe to repeat.

Do not use AsyncStorage for an offline mutation queue. It is a key-value store without transactions or queries, so concurrent read-modify-write cycles from the UI and a background task can overwrite each other. Use SQLite. Maintained options include expo-sqlite and @op-engineering/op-sqlite; WatermelonDB is an option if you want a full sync-aware ORM. (react-native-quick-sqlite, recommended in many older articles, is now marked deprecated on npm.)

A minimal schema:

CREATE TABLE IF NOT EXISTS sync_queue (
  id            TEXT PRIMARY KEY,      -- client-generated UUID, also the idempotency key
  created_at    INTEGER NOT NULL,      -- ordering
  endpoint      TEXT NOT NULL,
  payload       TEXT NOT NULL,         -- JSON body
  status        TEXT NOT NULL DEFAULT 'PENDING',  -- PENDING | IN_FLIGHT | DEAD
  attempts      INTEGER NOT NULL DEFAULT 0,
  next_attempt_at INTEGER NOT NULL DEFAULT 0,
  last_error    TEXT
);
CREATE INDEX IF NOT EXISTS idx_sync_queue_ready ON sync_queue (status, next_attempt_at, created_at);

The processor below uses the @op-engineering/op-sqlite API (open, and an async execute that returns { rows }, as of version 19). The same logic maps directly onto expo-sqlite.

// database/sync.ts
import { open } from '@op-engineering/op-sqlite';

const db = open({ name: 'app.db' });
const MAX_ATTEMPTS = 8;
let running = false; // one runner per JS runtime

type QueueRow = { id: string; endpoint: string; payload: string; attempts: number };

export async function processSyncQueue({ budgetMs }: { budgetMs: number }) {
  if (running) return;
  running = true;
  const deadline = Date.now() + budgetMs;

  try {
    // Rows left IN_FLIGHT by a run the OS killed have an unknown outcome.
    // Return them to PENDING; the idempotency key makes resending safe.
    await db.execute(`UPDATE sync_queue SET status = 'PENDING' WHERE status = 'IN_FLIGHT'`);

    while (Date.now() < deadline) {
      const { rows } = await db.execute(
        `SELECT id, endpoint, payload, attempts FROM sync_queue
         WHERE status = 'PENDING' AND next_attempt_at <= ?
         ORDER BY created_at LIMIT 1`,
        [Date.now()],
      );
      const job = rows[0] as QueueRow | undefined;
      if (!job) return;

      await db.execute(`UPDATE sync_queue SET status = 'IN_FLIGHT' WHERE id = ?`, [job.id]);
      const ok = await sendJob(job, deadline - Date.now());

      if (ok) {
        await db.execute(`DELETE FROM sync_queue WHERE id = ?`, [job.id]);
      } else {
        await scheduleRetry(job);
        return; // keep ordering: do not skip ahead of a failed mutation
      }
    }
  } finally {
    running = false;
  }
}

Important decisions in this code:

  • Recovery of IN_FLIGHT rows. If the OS killed the previous run after the request was sent but before the row was deleted, the outcome is unknown. Resetting to PENDING and resending is only safe because the server deduplicates by idempotency key.
  • One row at a time, oldest first. Sequential processing keeps causal order: a "create" is never sent after the "update" that depends on it. Stopping at the first failure preserves that order.
  • The running flag prevents two runners in the same JavaScript runtime (for example a foreground "sync now" and a background task) from sending the same row twice. It does not protect against two separate runtimes; the idempotency key covers that case.
  • The deadline stops the loop from starting new work when the time budget is spent.

The send and retry helpers:

// database/sync.ts (continued)
async function sendJob(job: QueueRow, remainingMs: number): Promise<boolean> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), Math.max(1_000, remainingMs));
  try {
    const response = await fetch(`https://api.example.com${job.endpoint}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'Idempotency-Key': job.id },
      body: job.payload,
      signal: controller.signal,
    });
    if (response.ok || response.status === 409) return true; // 409: already applied
    if (response.status >= 400 && response.status < 500 && response.status !== 429) {
      await markDead(job, `HTTP ${response.status}`);
      return true; // permanent failure: move it aside so the queue is not blocked
    }
    return false;
  } catch {
    return false; // offline, timeout or abort
  } finally {
    clearTimeout(timer);
  }
}

async function scheduleRetry(job: QueueRow) {
  const attempts = job.attempts + 1;
  if (attempts >= MAX_ATTEMPTS) return markDead(job, 'max attempts');
  const backoffMs = Math.min(60 * 60_000, 30_000 * 2 ** attempts);
  await db.execute(
    `UPDATE sync_queue SET status = 'PENDING', attempts = ?, next_attempt_at = ? WHERE id = ?`,
    [attempts, Date.now() + backoffMs, job.id],
  );
}

async function markDead(job: QueueRow, reason: string) {
  await db.execute(`UPDATE sync_queue SET status = 'DEAD', last_error = ? WHERE id = ?`, [
    reason,
    job.id,
  ]);
}

Notes on these helpers:

  • AbortController with fetch caps each request at the remaining budget, so a large upload does not start when only a second or two remain.
  • Treating 409 as success assumes your API returns it for a duplicate idempotency key. Match this to your backend's actual contract.
  • Permanent 4xx failures go to DEAD instead of blocking every later mutation forever. Surface DEAD rows in the UI so a user or support engineer can act on them. Whether a dead row should block later rows for the same record is a domain decision; this example does not block.
  • Backoff lives in the queue, not in the scheduler. The OS decides when the next run happens; next_attempt_at decides which rows that run is allowed to try.

Triggering Sync at the Right Moments

The background scheduler is the safety net, not the main path. A responsive app syncs whenever it has a chance:

  1. Right after a local write, if the device is online. Most mutations should leave the queue within seconds while the app is still in the foreground.
  2. When connectivity returns, using a network-state listener such as @react-native-community/netinfo.
  3. When the app returns to the foreground, via AppState changing to active.
  4. From the background task, for whatever the first three missed.

On iOS, if a write happens just before the user leaves the app, wrapping that single flush in beginBackgroundTask (exposed by some libraries, or via a small native module) gives it a short extra window. Keep the work small and end the task as soon as it is done.

Handling OS Preemption and Timeouts

On both platforms the OS can stop your background work early: when time runs out, when memory is needed, or, for iOS processing tasks, when the user picks up the device. Design for that:

  • Budget conservatively. The 25 second budget in the examples is an application choice, not a platform number. Neither Apple nor Google publishes a fixed run time for these tasks, so pick a budget that finishes comfortably and lets the next run continue.
  • Make every step restartable. The queue above can be killed between any two statements and still converge.
  • Use the expiration signals. expo-background-task provides addExpirationListener on iOS; react-native-background-fetch provides the timeout callback; native BGTask provides expirationHandler; WorkManager cancels a CoroutineWorker's coroutine on stop.
  • Move large files out of the JavaScript task. For photos and videos, a background URLSession on iOS or a WorkManager worker with setForeground on Android is a better fit than a JavaScript fetch in a short window.

Testing and Observability

Background code is hard to test because the OS decides when it runs. A practical plan:

What to verifyHow
Queue logic (ordering, retry, dead)Unit tests against an in-memory SQLite database, with fetch mocked to fail, time out and return 409
Task runs at all on Androidadb shell dumpsys jobscheduler to inspect scheduled jobs; WorkManager diagnostics with adb shell am broadcast -a "androidx.work.diagnostics.REQUEST_DIAGNOSTICS" -p <your.package>
Task runs at all on iOSPhysical device; trigger from the debugger using Apple's documented _simulateLaunchForTaskWithIdentifier command
Library wiring in dev buildsBackgroundTask.triggerTaskWorkerForTestingAsync() for expo-background-task
Doze behavioradb shell dumpsys deviceidle force-idle, then adb shell dumpsys deviceidle unforce
Recovery after killKill the app mid-sync, relaunch, confirm IN_FLIGHT rows are resent and the server deduplicates them

In production, log each run with a start time, rows sent, rows failed, and why it stopped (empty queue, budget, failure). Keep payload contents out of logs. Track queue depth and the age of the oldest pending row; a growing oldest-row age is the earliest signal that background sync is not running on some devices.

Android OEM Restrictions and iOS User Settings

Some Android manufacturers add battery management on top of stock Android that can delay or skip scheduled work. The behavior varies by vendor and OS version, which the Expo docs also call out. If sync timing matters, detect long gaps (oldest pending row older than a threshold) and guide users to the relevant battery setting in-app rather than assuming the scheduler always runs.

On iOS, users can turn off Background App Refresh globally or per app, and Low Power Mode reduces background activity. Check the library's status API and show a clear message when background work is restricted.

When Background Tasks Are Not Enough

If the product requires near-immediate delivery, such as continuous location tracking or a user watching an upload progress bar, deferrable background tasks are the wrong tool:

  • Android foreground services run immediately with a persistent notification. On Android 14+, each foreground service must declare a type, and some types require extra permissions.
  • iOS background modes such as location updates or audio exist for specific use cases and are reviewed against those use cases.
  • Silent push notifications can prompt a sync from the server side, but delivery is not guaranteed and the system may throttle it.

For typical business data such as CRM updates, field service reports and inventory counts, the combination in this guide (foreground flushes, a background scheduler as the safety net, and an idempotent queue) is a reasonable balance between delivery and battery use.

Getting this right takes both React Native and native platform knowledge. If your team is dealing with sync failures, background crashes or a hand-rolled bridge that broke after a React Native upgrade, our React Native app development services cover offline-first architecture and native module work.

Common Mistakes

  • Returning success before the work is done. Whether it is a Worker, a BGTask or a library callback, report completion only after the queue run has finished.
  • Defining the task inside a component. Background launches do not mount screens.
  • Assuming a schedule. "Every 15 minutes" is a minimum, not a promise.
  • Deleting rows before the server confirms. Delete only on a successful response.
  • Resending without an idempotency key. Any retry after an unknown outcome can create duplicates.
  • Letting one bad row block the queue forever. Move permanent failures to a dead state and surface them.
  • Testing only in the iOS simulator. The Background Tasks API is not supported there.

Production Readiness Checklist

  • Sync task registered at module scope and imported from the app entry point
  • Library or native bridge reports real success or failure to the OS
  • iOS Info.plist contains the required UIBackgroundModes and BGTaskSchedulerPermittedIdentifiers
  • Android long-running work uses setForeground with a declared foreground service type when targeting API 34+
  • Queue stored in SQLite with ordering, attempts, next_attempt_at and a dead state
  • Every mutation carries an idempotency key the server enforces
  • IN_FLIGHT rows are recovered on the next run
  • Each run has a time budget and honors the platform's expiration signal
  • Sync also runs after writes, on reconnect and on foreground
  • Queue depth and oldest-row age are monitored; restricted background status is shown to the user
  • Tested on physical devices, including Doze and kill-during-sync scenarios

Sources

If a sync engine is already failing in production and you want a second pair of eyes on it, book a free architecture review with our mobile and backend engineers.

Frequently Asked Questions

Why does background work fail in React Native apps?

iOS and Android suspend or limit apps in the background to save battery, so timers and in-memory work stop. Reliable sync needs the platform schedulers, WorkManager on Android and BGTaskScheduler on iOS, plus a persistent queue that can resume after being interrupted.

What is Headless JS in React Native?

Headless JS is an Android feature that runs a registered JavaScript task without mounting any UI, typically started from a native service. It does not retry by default; retries need a HeadlessJsRetryPolicy and a thrown HeadlessJsTaskError.

How long can a React Native app run in the background on iOS?

applicationDidEnterBackground has about five seconds to return. beginBackgroundTask can extend that for a limited, system-decided time. BGTaskScheduler tasks run when the system chooses; processing tasks can run for minutes but only while the device is idle, and can be stopped at any time.

Should I use expo-background-task or react-native-background-fetch?

Both wrap the platform schedulers. expo-background-task is simple and fits Expo or apps that already include expo. react-native-background-fetch offers more Android control, including headless runs after the app is terminated. Choose based on whether you need those Android options.

How do you make offline data sync reliable?

Write every change to a SQLite queue first, send rows in order with an idempotency key, delete a row only after the server confirms it, and recover rows whose outcome is unknown on the next run. Trigger sync in the foreground whenever possible and use background tasks as a safety net.

About the author

Badal Singh

Co-founder of SoftwareCrafting

Badal Singh is the Co-founder of SoftwareCrafting in Delhi and writes technical guides about web and mobile development, backend security, cloud infrastructure, DevOps, and developer tooling.

Writes about Next.js, React, Node.js, PostgreSQL, React Native, Flutter.

View author profile

Last updated: 2026-10-27