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