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

react-native.md

76 lines2.4 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 '@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 }
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 )
74```
75​
76In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.