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

react-native.md

139 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, 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​
10There is a 3rd party [Reactotron](https://github.com/infinitered/reactotron/) plugin which you can try: https://github.com/hsndmr/reactotron-react-query
11​
12If you would like to help us make the built-in devtools platform agnostic, please let us know!
13​
14## Online status management
15​
16React Query already supports auto refetch on reconnect in web browser.
17To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
18​
19```tsx
20import NetInfo from '@react-native-community/netinfo'
21import { onlineManager } from '@tanstack/react-query'
22​
23onlineManager.setEventListener(setOnline => {
24 return NetInfo.addEventListener(state => {
25 setOnline(!!state.isConnected)
26 })
27})
28```
29​
30## Refetch on App focus
31​
32Instead 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":
33​
34```tsx
35import { useEffect } from "react"
36import { AppState, Platform } from 'react-native'
37import type { AppStateStatus } from "react-native"
38import { focusManager } from '@tanstack/react-query'
39​
40function onAppStateChange(status: AppStateStatus) {
41 if (Platform.OS !== 'web') {
42 focusManager.setFocused(status === 'active')
43 }
45​
46useEffect(() => {
47 const subscription = AppState.addEventListener('change', onAppStateChange)
48​
49 return () => subscription.remove()
50}, [])
51```
52​
53## Refresh on Screen focus
54​
55In some situations, you may want to refetch the query when a React Native Screen is focused again.
56This custom hook will call the provided `refetch` function when the screen is focused again.
57​
58```tsx
59import React from 'react'
60import { useFocusEffect } from '@react-navigation/native'
61​
62export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
63 const firstTimeRef = React.useRef(true)
64​
65 useFocusEffect(
66 React.useCallback(() => {
67 if (firstTimeRef.current) {
68 firstTimeRef.current = false;
69 return;
70 }
71​
72 refetch()
73 }, [refetch])
74 )
76```
77​
78In the above code, `refetch` is skipped the first time because `useFocusEffect` calls our callback on mount in addition to screen focus.
79​
80## Disable re-renders on out of focus Screens
81​
82In 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.
83​
84This 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.
85​
86```tsx
87import React from 'react'
88import { NotifyOnChangeProps } from '@tanstack/query-core'
89import { useFocusEffect } from '@react-navigation/native'
90​
91export function useFocusNotifyOnChangeProps(notifyOnChangeProps?: NotifyOnChangeProps) {
92 const focusedRef = React.useRef(true)
93​
94 useFocusEffect(
95 React.useCallback(() => {
96 focusedRef.current = true
97​
98 return () => {
99 focusedRef.current = false
100 }
101 }, [])
102 )
103​
104 return () => {
105 if (!focusedRef.current) {
106 return []
107 }
108​
109 if (typeof notifyOnChangeProps === 'function') {
110 return notifyOnChangeProps()
111 }
112​
113 return notifyOnChangeProps.current
114 }
116```
117​
118In the above code, `useFocusEffect` is used to change the value of a reference that the callback will use as a condition.
119​
120The argument is wrapped in a reference to also guarantee that the returned callback always keeps the same reference.
121​
122Example usage:
123​
124```tsx
125function MyComponent() {
126 const notifyOnChangeProps = useFocusNotifyOnChangeProps();
127​
128 const { dataUpdatedAt } = useQuery({
129 queryKey: ['myKey'],
130 queryFn: async () => {
131 const response = await fetch('https://api.github.com/repos/tannerlinsley/react-query');
132 return response.json();
133 },
134 notifyOnChangeProps,
135 });
136​
137 return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>;
138};
139```