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

react-native.md

73 lines2.1 KB

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 }
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 )
71```
72​
73In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.