Capítulo 8 de 80

Chapter 8: React Native

Core Idea

React Query works out of the box in React Native, but two web-only refetch triggers (window focus, navigator.onLine) need manual wiring through onlineManager and focusManager since RN has no window.

Key Concepts

  • onlineManager: web's auto reconnect-refetch relies on browser online/offline events, which don't exist in RN — wire onlineManager.setEventListener to a network library (@react-native-community/netinfo or expo-network) to restore it.
  • focusManager: web's window-focus refetch has no RN equivalent either — wire it to React Native's AppState "change" event, calling focusManager.setFocused(status === 'active') only when Platform.OS !== 'web' (so web behavior is untouched in a universal app).
  • Per-screen refetch on navigation focus: a custom hook combining useFocusEffect (React Navigation) with queryClient.refetchQueries({ stale: true, type: 'active' }) refetches stale active queries when a screen regains focus — skip the initial mount call, since useFocusEffect also fires then.
  • subscribed option on useQuery: lets a query stop being subscribed to updates (no re-renders, no new fetches) while its screen is out of focus, driven by e.g. React Navigation's useIsFocused() — re-subscribing automatically when it flips back to true.
  • Devtools: no first-party in-app RN devtools; third-party options exist (Rozenite plugin for React Native DevTools, a native macOS debugging app, Flipper plugin, Reactotron plugin).

Code Examples

// Reconnect-refetch via NetInfo
onlineManager.setEventListener((setOnline) =>
  NetInfo.addEventListener((state) => setOnline(!!state.isConnected))
)

// Focus-refetch via AppState
function onAppStateChange(status: AppStateStatus) {
  if (Platform.OS !== 'web') focusManager.setFocused(status === 'active')
}
AppState.addEventListener('change', onAppStateChange)

// Unsubscribe a query while its screen is unfocused
const isFocused = useIsFocused()
useQuery({ queryKey: ['key'], queryFn, subscribed: isFocused })
  • What it demonstrates: the three RN-specific wiring points — network status, app focus, and per-screen subscription — layered on top of the same useQuery/useMutation API used on web.

Key Takeaways

  1. onlineManager and focusManager are the two managers to wire manually in any RN app — without them, reconnect/focus refetching silently doesn't happen.
  2. Guard focusManager.setFocused with Platform.OS !== 'web' in universal (web + native) codebases so you don't double-drive focus state.
  3. Use the subscribed option (not manual enabled toggling) to pause a query cleanly when its screen loses focus, in combination with React Navigation's useIsFocused.

Connects To

  • FocusManager / OnlineManager: the underlying manager APIs configured here.
  • Window Focus Refetching: the web-default behavior this chapter's focusManager wiring replaces for RN.