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

react-native.md

147 lines4.4 KB

1---
2id: react-native
3title: React Native
4---
5​
6React Query is designed to work out of the box with React Native.
7​
8## DevTools Support
9​
10There are several options available for React Native DevTools integration:
11​
121. **Native macOS App**: A 3rd party app for debugging React Query in any js-based application:
13 https://github.com/LovesWorking/rn-better-dev-tools
14​
152. **Flipper Plugin**: A 3rd party plugin for Flipper users:
16 https://github.com/bgaleotti/react-query-native-devtools
17​
183. **Reactotron Plugin**: A 3rd party plugin for Reactotron users:
19 https://github.com/hsndmr/reactotron-react-query
20​
21## Online status management
22​
23React Query already supports auto refetch on reconnect in web browser.
24To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
25​
26```tsx
27import NetInfo from '@react-native-community/netinfo'
28import { onlineManager } from '@tanstack/react-query'
29​
30onlineManager.setEventListener((setOnline) => {
31 return NetInfo.addEventListener((state) => {
32 setOnline(!!state.isConnected)
33 })
34})
35```
36​
37or
38​
39```tsx
40import { onlineManager } from '@tanstack/react-query'
41import * as Network from 'expo-network'
42​
43onlineManager.setEventListener((setOnline) => {
44 let initialised = false
45​
46 const eventSubscription = Network.addNetworkStateListener((state) => {
47 initialised = true
48 setOnline(!!state.isConnected)
49 })
50​
51 Network.getNetworkStateAsync()
52 .then((state) => {
53 if (!initialised) {
54 setOnline(!!state.isConnected)
55 }
56 })
57 .catch(() => {
58 // getNetworkStateAsync can reject on some platforms/SDK versions
59 })
60​
61 return eventSubscription.remove
62})
63```
64​
65## Refetch on App focus
66​
67Instead 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":
68​
69```tsx
70import { useEffect } from 'react'
71import { AppState, Platform } from 'react-native'
72import type { AppStateStatus } from 'react-native'
73import { focusManager } from '@tanstack/react-query'
74​
75function onAppStateChange(status: AppStateStatus) {
76 if (Platform.OS !== 'web') {
77 focusManager.setFocused(status === 'active')
78 }
80​
81useEffect(() => {
82 const subscription = AppState.addEventListener('change', onAppStateChange)
83​
84 return () => subscription.remove()
85}, [])
86```
87​
88## Refresh on Screen focus
89​
90In some situations, you may want to refetch the query when a React Native Screen is focused again.
91This custom hook will refetch **all active stale queries** when the screen is focused again.
92​
93```tsx
94import React from 'react'
95import { useFocusEffect } from '@react-navigation/native'
96import { useQueryClient } from '@tanstack/react-query'
97​
98export function useRefreshOnFocus() {
99 const queryClient = useQueryClient()
100 const firstTimeRef = React.useRef(true)
101​
102 useFocusEffect(
103 React.useCallback(() => {
104 if (firstTimeRef.current) {
105 firstTimeRef.current = false
106 return
107 }
108​
109 // refetch all stale active queries
110 queryClient.refetchQueries({
111 queryKey: ['posts'],
112 stale: true,
113 type: 'active',
114 })
115 }, [queryClient]),
116 )
118```
119​
120In the above code, the first focus (when the screen is initially mounted) is skipped because `useFocusEffect` calls our callback on mount in addition to screen focus.
121​
122## Disable queries on out of focus screens
123​
124If 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:
125​
126Example usage:
127​
128```tsx
129import React from 'react'
130import { useIsFocused } from '@react-navigation/native'
131import { useQuery } from '@tanstack/react-query'
132import { Text } from 'react-native'
133​
134function MyComponent() {
135 const isFocused = useIsFocused()
136​
137 const { dataUpdatedAt } = useQuery({
138 queryKey: ['key'],
139 queryFn: () => fetch(...),
140 subscribed: isFocused,
141 })
142​
143 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
145```
146​
147When 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.