Open History to see the last commit
1---
2id: react-native
3title: React Native
4---
5β
6React Query is designed to work out of the box with React Native, with the exception of the devtools, which are only supported with React DOM at this time.
7β
8There is a 3rd party [Expo](https://docs.expo.dev/) plugin which you can try: https://github.com/expo/dev-plugins/tree/main/packages/react-query
9β
10There is a 3rd party [Flipper](https://fbflipper.com/docs/getting-started/react-native/) plugin which you can try: https://github.com/bgaleotti/react-query-native-devtools
11β
12There is a 3rd party [Reactotron](https://github.com/infinitered/reactotron/) plugin which you can try: https://github.com/hsndmr/reactotron-react-query
13β
14If you would like to help us make the built-in devtools platform agnostic, please let us know!
15β
16## Online status management
17β
18React Query already supports auto refetch on reconnect in web browser.
19To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
20β
21```tsx
22import NetInfo from '@react-native-community/netinfo'
23import { onlineManager } from '@tanstack/react-query'
24β
25onlineManager.setEventListener((setOnline) => {
26 return NetInfo.addEventListener((state) => {
27 setOnline(!!state.isConnected)
28 })
29})
30```
31β
32or
33β
34```tsx
35import { onlineManager } from '@tanstack/react-query'
36import * as Network from 'expo-network'
37β
38onlineManager.setEventListener((setOnline) => {
39 return Network.addNetworkStateListener((state) => {
40 setOnline(state.isConnected)
41 })
42})
43```
44β
45## Refetch on App focus
46β
47Instead 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":
48β
49```tsx
50import { useEffect } from 'react'
51import { AppState, Platform } from 'react-native'
52import type { AppStateStatus } from 'react-native'
53import { focusManager } from '@tanstack/react-query'
54β
55function onAppStateChange(status: AppStateStatus) {
56 if (Platform.OS !== 'web') {
57 focusManager.setFocused(status === 'active')
58 }
59}
60β
61useEffect(() => {
62 const subscription = AppState.addEventListener('change', onAppStateChange)
63β
64 return () => subscription.remove()
65}, [])
66```
67β
68## Refresh on Screen focus
69β
70In some situations, you may want to refetch the query when a React Native Screen is focused again.
71This custom hook will call the provided `refetch` function when the screen is focused again.
72β
73```tsx
74import React from 'react'
75import { useFocusEffect } from '@react-navigation/native'
76β
77export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
78 const firstTimeRef = React.useRef(true)
79β
80 useFocusEffect(
81 React.useCallback(() => {
82 if (firstTimeRef.current) {
83 firstTimeRef.current = false
84 return
85 }
86β
87 refetch()
88 }, [refetch]),
89 )
90}
91```
92β
93In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.
94β
95## Disable re-renders on out of focus Screens
96β
97In some situations, including performance concerns, you may want to stop re-renders when a React Native screen gets out of focus. To achieve this we can use `useFocusEffect` from `@react-navigation/native` together with the `notifyOnChangeProps` query option.
98β
99This custom hook provides a `notifyOnChangeProps` option that will return an empty array whenever a screen goes out of focus - effectively stopping any re-renders on that scenario. Whenever the screens gets in focus again, the behavior goes back to normal.
100β
101```tsx
102import React from 'react'
103import { NotifyOnChangeProps } from '@tanstack/query-core'
104import { useFocusEffect } from '@react-navigation/native'
105β
106export function useFocusNotifyOnChangeProps(
107 notifyOnChangeProps?: NotifyOnChangeProps,
108) {
109 const focusedRef = React.useRef(true)
110β
111 useFocusEffect(
112 React.useCallback(() => {
113 focusedRef.current = true
114β
115 return () => {
116 focusedRef.current = false
117 }
118 }, []),
119 )
120β
121 return () => {
122 if (!focusedRef.current) {
123 return []
124 }
125β
126 if (typeof notifyOnChangeProps === 'function') {
127 return notifyOnChangeProps()
128 }
129β
130 return notifyOnChangeProps
131 }
132}
133```
134β
135In the above code, `useFocusEffect` is used to change the value of a reference that the callback will use as a condition.
136β
137The argument is wrapped in a reference to also guarantee that the returned callback always keeps the same reference.
138β
139Example usage:
140β
141```tsx
142function MyComponent() {
143 const notifyOnChangeProps = useFocusNotifyOnChangeProps()
144β
145 const { dataUpdatedAt } = useQuery({
146 queryKey: ['myKey'],
147 queryFn: async () => {
148 const response = await fetch(
149 'https://api.github.com/repos/tannerlinsley/react-query',
150 )
151 return response.json()
152 },
153 notifyOnChangeProps,
154 })
155β
156 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
157}
158```
159β
160## Disable queries on out of focus screens
161β
162Enabled can also be set to a callback to support disabling queries on out of focus screens without state and re-rendering on navigation, similar to how notifyOnChangeProps works but in addition it wont trigger refetching when invalidating queries with refetchType active.
163β
164```tsx
165import React from 'react'
166import { useFocusEffect } from '@react-navigation/native'
167β
168export function useQueryFocusAware(notifyOnChangeProps?: NotifyOnChangeProps) {
169 const focusedRef = React.useRef(true)
170β
171 useFocusEffect(
172 React.useCallback(() => {
173 focusedRef.current = true
174β
175 return () => {
176 focusedRef.current = false
177 }
178 }, []),
179 )
180β
181 return () => focusedRef.current
182}
183```
184β
185Example usage:
186β
187```tsx
188function MyComponent() {
189 const isFocused = useQueryFocusAware()
190β
191 const { dataUpdatedAt } = useQuery({
192 queryKey: ['key'],
193 queryFn: () => fetch(...),
194 enabled: isFocused,
195 })
196β
197 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
198}
199```