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

react-native.md

122 lines4.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 [Expo](https://docs.expo.dev/) plugin which you can try: https://github.com/expo/dev-plugins/tree/main/packages/react-query
9​
10There 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
11​
12There is a 3rd party [Reactotron](https://github.com/infinitered/reactotron/) plugin which you can try: https://github.com/hsndmr/reactotron-react-query
13​
14If you would like to help us make the built-in devtools platform agnostic, please let us know!
15​
16## Online status management
17​
18React Query already supports auto refetch on reconnect in web browser.
19To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
20​
21```tsx
22import NetInfo from '@react-native-community/netinfo'
23import { onlineManager } from '@tanstack/react-query'
24​
25onlineManager.setEventListener((setOnline) => {
26 const eventSubscribtion = NetInfo.addEventListener((state) => {
27 setOnline(!!state.isConnected)
28 })
29 return eventSubscribtion.remove
30})
31```
32​
33or
34​
35```tsx
36import { onlineManager } from '@tanstack/react-query'
37import * as Network from 'expo-network'
38​
39onlineManager.setEventListener((setOnline) => {
40 const eventSubscribtion = Network.addNetworkStateListener((state) => {
41 setOnline(!!state.isConnected)
42 })
43 return eventSubscribtion.remove
44})
45```
46​
47## Refetch on App focus
48​
49Instead 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":
50​
51```tsx
52import { useEffect } from 'react'
53import { AppState, Platform } from 'react-native'
54import type { AppStateStatus } from 'react-native'
55import { focusManager } from '@tanstack/react-query'
56​
57function onAppStateChange(status: AppStateStatus) {
58 if (Platform.OS !== 'web') {
59 focusManager.setFocused(status === 'active')
60 }
62​
63useEffect(() => {
64 const subscription = AppState.addEventListener('change', onAppStateChange)
65​
66 return () => subscription.remove()
67}, [])
68```
69​
70## Refresh on Screen focus
71​
72In some situations, you may want to refetch the query when a React Native Screen is focused again.
73This custom hook will call the provided `refetch` function when the screen is focused again.
74​
75```tsx
76import React from 'react'
77import { useFocusEffect } from '@react-navigation/native'
78​
79export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
80 const firstTimeRef = React.useRef(true)
81​
82 useFocusEffect(
83 React.useCallback(() => {
84 if (firstTimeRef.current) {
85 firstTimeRef.current = false
86 return
87 }
88​
89 refetch()
90 }, [refetch]),
91 )
93```
94​
95In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.
96​
97## Disable queries on out of focus screens
98​
99If you don’t want certain queries to remain “live” while a screen is out of focus, you can use the subscribed prop on useQuery. This prop lets you control whether a query stays subscribed to updates. Combined with React Navigation’s useIsFocused, it allows you to seamlessly unsubscribe from queries when a screen isn’t in focus:
100​
101Example usage:
102​
103```tsx
104import React from 'react'
105import { useIsFocused } from '@react-navigation/native'
106import { useQuery } from '@tanstack/react-query'
107import { Text } from 'react-native'
108​
109function MyComponent() {
110 const isFocused = useIsFocused()
111​
112 const { dataUpdatedAt } = useQuery({
113 queryKey: ['key'],
114 queryFn: () => fetch(...),
115 subscribed: isFocused,
116 })
117​
118 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
120```
121​
122When subscribed is false, the query unsubscribes from updates and won’t trigger re-renders or fetch new data for that screen. Once it becomes true again (e.g., when the screen regains focus), the query re-subscribes and stays up to date.