Skip to main content

Lesson 3 of 9

Offline-First - NetInfo & Queue Mutations

Mobile apps must handle network loss gracefully. Offline-first means the app shows cached data immediately, queues mutations made offline, and replays them when connectivity returns.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Offline Banner + TanStack Query Offline Mode

Offline Banner + TanStack Query Offline Mode
import NetInfo from '@react-native-community/netinfo';
import { onlineManager } from '@tanstack/react-query';

// Tell TanStack Query to use NetInfo for connectivity detection
// This pauses queries and mutations when offline, resumes when back online
onlineManager.setEventListener(setOnline => {
  const unsub = NetInfo.addEventListener(state => {
    setOnline(!!state.isConnected && !!state.isInternetReachable);
  });
  return unsub;
});

// ---- Offline mutation queue ----
// TanStack Query automatically retries mutations when back online
// with the 'retry' option set:
const mutation = useMutation({
  mutationFn: createPost,
  retry: Infinity,   // keep retrying until online
  retryDelay: 1000,
  networkMode: 'offlineFirst', // execute mutation even when offline (stores in queue)
});

// ---- useNetworkStatus hook for UI (from Module 5) ----
function OfflineBanner() {
  const { isConnected } = useNetworkStatus();

  if (isConnected) return null;
  return (
    <View style={{ backgroundColor: '#dc2626', paddingVertical: 6, paddingHorizontal: 16 }}>
      <Text style={{ color: 'white', textAlign: 'center', fontSize: 13, fontWeight: '600' }}>
        โšก No internet - showing cached content
      </Text>
    </View>
  );
}

function useNetworkStatus() {
  const [isConnected, setIsConnected] = React.useState(true);
  React.useEffect(() => {
    const unsub = NetInfo.addEventListener(s => setIsConnected(!!s.isConnected));
    return unsub;
  }, []);
  return { isConnected };
}

Tip

Tip

Practice OfflineFirst NetInfo Queue Mutations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Queueing offline mutations in MMKV and syncing automatically upon reconnection

Practice Task

Note

Practice Task - (1) Write a working example of OfflineFirst NetInfo Queue Mutations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with OfflineFirst NetInfo Queue Mutations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done