Blog>
Snippets

Combining focusManager and onlineManager for Efficient Data Sync

Offer a code example that combines focusManager and onlineManager to create an efficient data synchronization strategy that minimizes bandwidth usage and optimizes application responsiveness.
import { useEffect } from 'react';
import NetInfo from '@react-native-community/netinfo';
import { focusManager, onlineManager } from 'react-query';
import { AppState } from 'react-native';
This code imports necessary dependencies including useEffect hook from React, NetInfo for network information, focusManager and onlineManager from react-query and AppState from react-native for app state management.
useEffect(() => {
  const handleConnectivityChange = (state) => {
    const isOnline = state.isConnected && Boolean(state.isInternetReachable);
    onlineManager.setOnline(isOnline);
  };

  const unsubscribe = NetInfo.addEventListener(handleConnectivityChange);

  return () => unsubscribe();
}, []);
This useEffect hook adds an event listener to NetInfo to monitor connectivity changes. It then updates the online status in onlineManager accordingly. It also cleans up by unsubscribing from the event listener on component unmount.
useEffect(() => {
  const handleAppStateChange = (nextAppState) => {
    const isAppActive = nextAppState === 'active';
    focusManager.setFocused(isAppActive);
  };

  const subscription = AppState.addEventListener('change', handleAppStateChange);

  return () => subscription.remove();
}, []);
This useEffect hook listens for app state changes using AppState from react-native. When the app state changes to 'active', it uses focusManager to indicate the app is in focus. It sets up and cleans the subscription to app state changes.
useEffect(() => {
  const subscription = AppState.addEventListener('change', (nextAppState) => {
    if (nextAppState === 'active') {
      // Perform data sync logic here when the app comes to foreground
    }
  });

  return () => subscription.remove();
}, []);
This useEffect hook uses AppState to determine when the app returns to an 'active' state (i.e., comes into the foreground). Upon activation, you can place data sync logic inside the if statement to efficiently sync data when the app is active, leveraging both focusManager and onlineManager.