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 '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β
30In React Native you have to use React Query `focusManager` to refetch when the App is focused.
31β
32```ts
33import { focusManager } from 'react-query'
34β
35function onAppStateChange(status: AppStateStatus) {
36 if (Platform.OS !== 'web') {
37 focusManager.setFocused(status === 'active')
38 }
39}
40β
41useEffect(() => {
42 const subscription = AppState.addEventListener('change', onAppStateChange)
43β
44 return () => subscription.remove()
45}, [])
46```
47β
48## Refresh on Screen focus
49β
50In some situations, you may want to refetch the query when a React Native Screen is focused again.
51This custom hook will call the provided `refetch` function when the screen is focused again.
52β
53```ts
54import React from 'react'
55import { useFocusEffect } from '@react-navigation/native'
56β
57export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
58 const firstTimeRef = React.useRef(true)
59β
60 useFocusEffect(
61 React.useCallback(() => {
62 if (firstTimeRef.current) {
63 firstTimeRef.current = false;
64 return;
65 }
66β
67 refetch()
68 }, [refetch])
69 )
70}
71```
72β
73In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.