TanStack Query React Native code for onlineManager and focusManager beside a phone order list

TanStack Query React Native support uses the same @tanstack/react-query package as the web, so hooks, keys and mutations work identically on iOS and Android. The difference is the environment: mobile apps have no browser window focus events and no built-in online detection, so you connect those signals yourself.

This article walks through installing the library in a React Native or Expo app, wiring connectivity and app focus, refetching when a screen gains focus and keeping data across restarts. There is no separate download for iOS; the library installs into your JavaScript project.

Installing in a Mobile Project

Add the core package with your project's package manager. Connectivity detection relies on the community NetInfo module, which bare React Native apps install directly and Expo apps add through the Expo installer.

Terminal
npm install @tanstack/react-query
npm install @react-native-community/netinfo
# Expo projects
npx expo install @react-native-community/netinfo

Creating the Provider

The provider setup matches the web exactly. Create one QueryClient at module level and wrap your root navigator, so every screen shares the same cache.

App.tsx
const queryClient = new QueryClient();

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <RootNavigator />
    </QueryClientProvider>
  );
}

Wiring Online Status

On the web, React Query listens to browser online events. In React Native you pass NetInfo state to onlineManager instead. Queries pause while the device is offline and resume automatically when the connection returns.

onlineManager.ts
import NetInfo from '@react-native-community/netinfo';
import { onlineManager } from '@tanstack/react-query';

onlineManager.setEventListener((setOnline) =>
  NetInfo.addEventListener((state) => {
    setOnline(!!state.isConnected);
  })
);

Refetching When the App Returns

Mobile users switch apps constantly. React Native's AppState tells you when your app moves back to the foreground, and focusManager turns that signal into the same refetch behavior that window focus triggers on the web.

App.tsx
import { AppState, Platform } from 'react-native';
import { focusManager } from '@tanstack/react-query';

function onAppStateChange(status) {
  if (Platform.OS !== 'web') {
    focusManager.setFocused(status === 'active');
  }
}

useEffect(() => {
  const sub = AppState.addEventListener('change', onAppStateChange);
  return () => sub.remove();
}, []);

Refreshing Data on Screen Focus

Navigation libraries keep previous screens mounted, so returning to a screen does not remount its queries. Use your navigator's focus hook to refetch stale data when a screen becomes visible again, skipping the first focus to avoid a duplicate request.

Pull to Refresh

FlatList and ScrollView accept a refreshing flag and an onRefresh handler. Connect them to the refetch function returned by useQuery so users can force an update with a familiar gesture.

OrdersScreen.tsx
const { data, refetch, isRefetching } = useQuery({
  queryKey: ['orders'],
  queryFn: fetchOrders,
});

<FlatList data={data} renderItem={renderOrder}
  refreshing={isRefetching} onRefresh={refetch} />

Persisting the Cache Between Launches

The cache lives in memory by default, so a cold start shows loading states again. The persistence packages save selected queries to device storage and restore them on launch, letting users see recent data immediately while fresh requests run.

PackageRole
@tanstack/react-query-persist-clientProvides PersistQueryClientProvider
@tanstack/query-async-storage-persisterSaves the cache to AsyncStorage
@react-native-async-storage/async-storageDevice storage used by the persister

What Not to Persist

Avoid saving tokens, personal records or anything sensitive in plain storage. Set a maxAge so old data expires, and clear the persisted cache when a user signs out.

Debugging on Mobile

The browser DevTools panel cannot render inside a native app. Community plugins for mobile debuggers can display the cache, and logging query states during development also helps. The DevTools article describes the web panel these plugins imitate.

  • Log onlineManager.isOnline() while testing airplane mode.
  • Check that AppState events fire when switching apps.
  • Verify persisted data clears on sign out.

Choosing staleTime for Mobile Networks

Mobile connections are slower and less reliable than office broadband, so aggressive refetching can waste data and battery. A modest staleTime for lists and profile screens reduces background traffic while still refreshing when users return to the app after a longer break.

Data that changes rapidly, such as delivery status or chat messages, can keep a short staleTime or use a refetchInterval while the screen is visible. Pause intervals when the app goes to the background so the device is not polling unnecessarily.

Handling Authentication

Most mobile apps attach an access token to every request. Read the token inside the query function rather than placing it in the query key, so keys stay readable and tokens never appear in logs or persisted storage.

When a user signs out, clear the query cache and any persisted copy before showing the sign-in screen. This prevents the next account on a shared device from briefly seeing old data during startup.

Retrying Requests Sensibly

The default retry count works for most apps, but mobile users who are offline will see paused queries rather than failures. Keep retries for server errors and consider turning them off for responses such as not found or unauthorized, which will not succeed on a second attempt.

Testing on Real Devices

Simulators rarely reproduce real network conditions. Test on physical devices with airplane mode, weak signal and app switching to confirm that paused queries resume, focus refetching fires and the persisted cache restores correctly after the app is closed.

Structuring a Mobile Codebase

Keep connectivity and focus wiring in a dedicated setup file imported once at app startup, so screens never repeat it. Group query hooks by feature, matching your navigation structure, which makes it easy to find the hook behind any screen.

Shared logic between a React web app and a React Native app can live in a common package. Because both platforms use the same library, query hooks and key factories move between them unchanged, while only the platform setup differs.

Measuring Network Usage

Track how many requests each screen makes during a typical session. If a screen refetches every time it gains focus but its data rarely changes, raising staleTime cuts traffic without hurting freshness for users. Battery usage benefits from the same change.

TanStack Query React Native FAQ

Is there a React Query download for iOS?

No. React Query is a JavaScript library, not an app. Install it with npm or Yarn inside a React Native project and it runs on iOS and Android.

Does it work with Expo?

Yes. Expo apps use the same packages, installing native modules such as NetInfo through the Expo CLI.

Do mutations work offline?

Mutations pause while offline and resume when connectivity returns, provided the app stays open. Surviving restarts requires persistence and default mutation functions.

Conclusion

TanStack Query React Native setups need only two additions to the web pattern: connect NetInfo to onlineManager and AppState to focusManager. Everything else, from keys to mutations, transfers directly.

Follow the React Query tutorial for the core hooks, and review caching behavior to choose staleTime values that suit mobile networks.