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

react-native.md

149 lines4.6 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. **Rozenite Plugin**: A 3rd party plugin for [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) users: https://www.rozenite.dev/docs/official-plugins/tanstack-query
13​
142. **Native macOS App**: A 3rd party app for debugging React Query in any js-based application:
15 https://github.com/LovesWorking/rn-better-dev-tools
16​
173. **Flipper Plugin**: A 3rd party plugin for Flipper users:
18 https://github.com/bgaleotti/react-query-native-devtools
19​
204. **Reactotron Plugin**: A 3rd party plugin for Reactotron users:
21 https://github.com/hsndmr/reactotron-react-query
22​
23## Online status management
24​
25React Query already supports auto refetch on reconnect in web browser.
26To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
27​
28```tsx
29import NetInfo from '@react-native-community/netinfo'
30import { onlineManager } from '@tanstack/react-query'
31​
32onlineManager.setEventListener((setOnline) => {
33 return NetInfo.addEventListener((state) => {
34 setOnline(!!state.isConnected)
35 })
36})
37```
38​
39or
40​
41```tsx
42import { onlineManager } from '@tanstack/react-query'
43import * as Network from 'expo-network'
44​
45onlineManager.setEventListener((setOnline) => {
46 let initialised = false
47​
48 const eventSubscription = Network.addNetworkStateListener((state) => {
49 initialised = true
50 setOnline(!!state.isConnected)
51 })
52​
53 Network.getNetworkStateAsync()
54 .then((state) => {
55 if (!initialised) {
56 setOnline(!!state.isConnected)
57 }
58 })
59 .catch(() => {
60 // getNetworkStateAsync can reject on some platforms/SDK versions
61 })
62​
63 return eventSubscription.remove
64})
65```
66​
67## Refetch on App focus
68​
69Instead 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":
70​
71```tsx
72import { useEffect } from 'react'
73import { AppState, Platform } from 'react-native'
74import type { AppStateStatus } from 'react-native'
75import { focusManager } from '@tanstack/react-query'
76​
77function onAppStateChange(status: AppStateStatus) {
78 if (Platform.OS !== 'web') {
79 focusManager.setFocused(status === 'active')
80 }
82​
83useEffect(() => {
84 const subscription = AppState.addEventListener('change', onAppStateChange)
85​
86 return () => subscription.remove()
87}, [])
88```
89​
90## Refresh on Screen focus
91​
92In some situations, you may want to refetch the query when a React Native Screen is focused again.
93This custom hook will refetch **all active stale queries** when the screen is focused again.
94​
95```tsx
96import React from 'react'
97import { useFocusEffect } from '@react-navigation/native'
98import { useQueryClient } from '@tanstack/react-query'
99​
100export function useRefreshOnFocus() {
101 const queryClient = useQueryClient()
102 const firstTimeRef = React.useRef(true)
103​
104 useFocusEffect(
105 React.useCallback(() => {
106 if (firstTimeRef.current) {
107 firstTimeRef.current = false
108 return
109 }
110​
111 // refetch all stale active queries
112 queryClient.refetchQueries({
113 queryKey: ['posts'],
114 stale: true,
115 type: 'active',
116 })
117 }, [queryClient]),
118 )
120```
121​
122In 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.
123​
124## Disable queries on out of focus screens
125​
126If 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:
127​
128Example usage:
129​
130```tsx
131import React from 'react'
132import { useIsFocused } from '@react-navigation/native'
133import { useQuery } from '@tanstack/react-query'
134import { Text } from 'react-native'
135​
136function MyComponent() {
137 const isFocused = useIsFocused()
138​
139 const { dataUpdatedAt } = useQuery({
140 queryKey: ['key'],
141 queryFn: () => fetch(...),
142 subscribed: isFocused,
143 })
144​
145 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
147```
148​
149When 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.