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 [Flipper](https://fbflipper.com/docs/getting-started/react-native/) plugin which you can try: https://github.com/bgaleotti/react-query-native-devtools
9β
10There is a 3rd party [Reactotron](https://github.com/infinitered/reactotron/) plugin which you can try: https://github.com/hsndmr/reactotron-react-query
11β
12If you would like to help us make the built-in devtools platform agnostic, please let us know!
13β
14## Online status management
15β
16React Query already supports auto refetch on reconnect in web browser.
17To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
18β
19```tsx
20import NetInfo from '@react-native-community/netinfo'
21import { onlineManager } from '@tanstack/react-query'
22β
23onlineManager.setEventListener(setOnline => {
24 return NetInfo.addEventListener(state => {
25 setOnline(!!state.isConnected)
26 })
27})
28```
29β
30## Refetch on App focus
31β
32Instead 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":
33β
34```tsx
35import { useEffect } from "react"
36import { AppState, Platform } from 'react-native'
37import type { AppStateStatus } from "react-native"
38import { focusManager } from '@tanstack/react-query'
39β
40function onAppStateChange(status: AppStateStatus) {
41 if (Platform.OS !== 'web') {
42 focusManager.setFocused(status === 'active')
43 }
44}
45β
46useEffect(() => {
47 const subscription = AppState.addEventListener('change', onAppStateChange)
48β
49 return () => subscription.remove()
50}, [])
51```
52β
53## Refresh on Screen focus
54β
55In some situations, you may want to refetch the query when a React Native Screen is focused again.
56This custom hook will call the provided `refetch` function when the screen is focused again.
57β
58```tsx
59import React from 'react'
60import { useFocusEffect } from '@react-navigation/native'
61β
62export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
63 const firstTimeRef = React.useRef(true)
64β
65 useFocusEffect(
66 React.useCallback(() => {
67 if (firstTimeRef.current) {
68 firstTimeRef.current = false;
69 return;
70 }
71β
72 refetch()
73 }, [refetch])
74 )
75}
76```
77β
78In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.