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

react-native.md

176 lines5.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 [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 return NetInfo.addEventListener((state) => {
27 setOnline(!!state.isConnected)
28 })
29})
30```
31​
32## Refetch on App focus
33​
34Instead 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":
35​
36```tsx
37import { useEffect } from 'react'
38import { AppState, Platform } from 'react-native'
39import type { AppStateStatus } from 'react-native'
40import { focusManager } from '@tanstack/react-query'
41​
42function onAppStateChange(status: AppStateStatus) {
43 if (Platform.OS !== 'web') {
44 focusManager.setFocused(status === 'active')
45 }
47​
48useEffect(() => {
49 const subscription = AppState.addEventListener('change', onAppStateChange)
50​
51 return () => subscription.remove()
52}, [])
53```
54​
55## Refresh on Screen focus
56​
57In some situations, you may want to refetch the query when a React Native Screen is focused again.
58This custom hook will call the provided `refetch` function when the screen is focused again.
59​
60```tsx
61import React from 'react'
62import { useFocusEffect } from '@react-navigation/native'
63​
64export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
65 const firstTimeRef = React.useRef(true)
66​
67 useFocusEffect(
68 React.useCallback(() => {
69 if (firstTimeRef.current) {
70 firstTimeRef.current = false
71 return
72 }
73​
74 refetch()
75 }, [refetch]),
76 )
78```
79​
80In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.
81​
82## Disable re-renders on out of focus Screens
83​
84In some situations, including performance concerns, you may want to stop re-renders when a React Native screen gets out of focus. To achieve this we can use `useFocusEffect` from `@react-navigation/native` together with the `notifyOnChangeProps` query option.
85​
86This custom hook provides a `notifyOnChangeProps` option that will return an empty array whenever a screen goes out of focus - effectively stopping any re-renders on that scenario. Whenever the screens gets in focus again, the behavior goes back to normal.
87​
88```tsx
89import React from 'react'
90import { NotifyOnChangeProps } from '@tanstack/query-core'
91import { useFocusEffect } from '@react-navigation/native'
92​
93export function useFocusNotifyOnChangeProps(
94 notifyOnChangeProps?: NotifyOnChangeProps,
95) {
96 const focusedRef = React.useRef(true)
97​
98 useFocusEffect(
99 React.useCallback(() => {
100 focusedRef.current = true
101​
102 return () => {
103 focusedRef.current = false
104 }
105 }, []),
106 )
107​
108 return () => {
109 if (!focusedRef.current) {
110 return []
111 }
112​
113 if (typeof notifyOnChangeProps === 'function') {
114 return notifyOnChangeProps()
115 }
116​
117 return notifyOnChangeProps
118 }
120```
121​
122In the above code, `useFocusEffect` is used to change the value of a reference that the callback will use as a condition.
123​
124The argument is wrapped in a reference to also guarantee that the returned callback always keeps the same reference.
125​
126Example usage:
127​
128```tsx
129function MyComponent() {
130 const notifyOnChangeProps = useFocusNotifyOnChangeProps()
131​
132 const { dataUpdatedAt } = useQuery({
133 queryKey: ['myKey'],
134 queryFn: async () => {
135 const response = await fetch(
136 'https://api.github.com/repos/tannerlinsley/react-query',
137 )
138 return response.json()
139 },
140 notifyOnChangeProps,
141 })
142​
143 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
145```
146​
147## Disable queries on out of focus screens
148​
149Enabled can also be set to a callback to support disabling queries on out of focus screens without state and re-rendering on navigation, similar to how notifyOnChangeProps works but in addition it wont trigger refetching when invalidating queries with refetchType active.
150​
151```tsx
152import React from 'react'
153import { useFocusEffect } from '@react-navigation/native'
154​
155export function useQueryFocusAware(notifyOnChangeProps?: NotifyOnChangeProps) {
156 const focusedRef = React.useRef(true)
157​
158 useFocusEffect(
159 React.useCallback(() => {
160 focusedRef.current = true
161​
162 return () => {
163 focusedRef.current = false
164 }
165 }, []),
166 )
167​
168 return () => focusedRef.current
169​
170 useQuery({
171 queryKey: ['key'],
172 queryFn: () => fetch(...),
173 enabled: () => focusedRef.current,
174 })
176```