Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

react-native.md

133 lines4.1 KB

1---
2id: react-native
3title: React Native
4---
5​
6React Query is designed to work out of the box with React Native.
7​
8## DevTools Support
9​
10There are several options available for React Native DevTools integration:
11​
121. **Native macOS App**: A 3rd party app for debugging React Query in any js-based application:
13 https://github.com/LovesWorking/rn-better-dev-tools
14​
152. **Flipper Plugin**: A 3rd party plugin for Flipper users:
16 https://github.com/bgaleotti/react-query-native-devtools
17​
183. **Reactotron Plugin**: A 3rd party plugin for Reactotron users:
19 https://github.com/hsndmr/reactotron-react-query
20​
21## Online status management
22​
23React Query already supports auto refetch on reconnect in web browser.
24To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
25​
26```tsx
27import NetInfo from '@react-native-community/netinfo'
28import { onlineManager } from '@tanstack/react-query'
29​
30onlineManager.setEventListener((setOnline) => {
31 return NetInfo.addEventListener((state) => {
32 setOnline(!!state.isConnected)
33 })
34})
35```
36​
37or
38​
39```tsx
40import { onlineManager } from '@tanstack/react-query'
41import * as Network from 'expo-network'
42​
43onlineManager.setEventListener((setOnline) => {
44 const eventSubscription = Network.addNetworkStateListener((state) => {
45 setOnline(!!state.isConnected)
46 })
47 return eventSubscription.remove
48})
49```
50​
51## Refetch on App focus
52​
53Instead of event listeners on `window`, React Native provides focus information through the [`AppState` module](https://reactnative.dev/docs/appstate#app-states). You can use the `AppState` "change" event to trigger an update when the app state changes to "active":
54​
55```tsx
56import { useEffect } from 'react'
57import { AppState, Platform } from 'react-native'
58import type { AppStateStatus } from 'react-native'
59import { focusManager } from '@tanstack/react-query'
60​
61function onAppStateChange(status: AppStateStatus) {
62 if (Platform.OS !== 'web') {
63 focusManager.setFocused(status === 'active')
64 }
66​
67useEffect(() => {
68 const subscription = AppState.addEventListener('change', onAppStateChange)
69​
70 return () => subscription.remove()
71}, [])
72```
73​
74## Refresh on Screen focus
75​
76In some situations, you may want to refetch the query when a React Native Screen is focused again.
77This custom hook will refetch **all active stale queries** when the screen is focused again.
78​
79```tsx
80import React from 'react'
81import { useFocusEffect } from '@react-navigation/native'
82import { useQueryClient } from '@tanstack/react-query'
83​
84export function useRefreshOnFocus() {
85 const queryClient = useQueryClient()
86 const firstTimeRef = React.useRef(true)
87​
88 useFocusEffect(
89 React.useCallback(() => {
90 if (firstTimeRef.current) {
91 firstTimeRef.current = false
92 return
93 }
94​
95 // refetch all stale active queries
96 queryClient.refetchQueries({
97 queryKey: ['posts'],
98 stale: true,
99 type: 'active',
100 })
101 }, [queryClient]),
102 )
104```
105​
106In the above code, the first focus (when the screen is initially mounted) is skipped because `useFocusEffect` calls our callback on mount in addition to screen focus.
107​
108## Disable queries on out of focus screens
109​
110If you don’t want certain queries to remain “live” while a screen is out of focus, you can use the subscribed prop on useQuery. This prop lets you control whether a query stays subscribed to updates. Combined with React Navigation’s useIsFocused, it allows you to seamlessly unsubscribe from queries when a screen isn’t in focus:
111​
112Example usage:
113​
114```tsx
115import React from 'react'
116import { useIsFocused } from '@react-navigation/native'
117import { useQuery } from '@tanstack/react-query'
118import { Text } from 'react-native'
119​
120function MyComponent() {
121 const isFocused = useIsFocused()
122​
123 const { dataUpdatedAt } = useQuery({
124 queryKey: ['key'],
125 queryFn: () => fetch(...),
126 subscribed: isFocused,
127 })
128​
129 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
131```
132​
133When subscribed is false, the query unsubscribes from updates and won’t trigger re-renders or fetch new data for that screen. Once it becomes true again (e.g., when the screen regains focus), the query re-subscribes and stays up to date.