React Native

· abundance's blog


React 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.

There is a 3rd party Expo plugin which you can try: https://github.com/expo/dev-plugins/tree/main/packages/react-query

There is a 3rd party Flipper plugin which you can try: https://github.com/bgaleotti/react-query-native-devtools

There is a 3rd party Reactotron plugin which you can try: https://github.com/hsndmr/reactotron-react-query

If you would like to help us make the built-in devtools platform agnostic, please let us know!

Online status management #

React Query already supports auto refetch on reconnect in web browser. To add this behavior in React Native you have to use React Query onlineManager as in the example below:

1import NetInfo from '@react-native-community/netinfo'
2import { onlineManager } from '@tanstack/react-query'
3
4onlineManager.setEventListener((setOnline) => {
5  return NetInfo.addEventListener((state) => {
6    setOnline(!!state.isConnected)
7  })
8})

Refetch on App focus #

Instead of event listeners on window, React Native provides focus information through the AppState module. You can use the AppState "change" event to trigger an update when the app state changes to "active":

 1import { useEffect } from 'react'
 2import { AppState, Platform } from 'react-native'
 3import type { AppStateStatus } from 'react-native'
 4import { focusManager } from '@tanstack/react-query'
 5
 6function onAppStateChange(status: AppStateStatus) {
 7  if (Platform.OS !== 'web') {
 8    focusManager.setFocused(status === 'active')
 9  }
10}
11
12useEffect(() => {
13  const subscription = AppState.addEventListener('change', onAppStateChange)
14
15  return () => subscription.remove()
16}, [])

Refresh on Screen focus #

In some situations, you may want to refetch the query when a React Native Screen is focused again. This custom hook will call the provided refetch function when the screen is focused again.

 1import React from 'react'
 2import { useFocusEffect } from '@react-navigation/native'
 3
 4export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
 5  const firstTimeRef = React.useRef(true)
 6
 7  useFocusEffect(
 8    React.useCallback(() => {
 9      if (firstTimeRef.current) {
10        firstTimeRef.current = false
11        return
12      }
13
14      refetch()
15    }, [refetch]),
16  )
17}

In the above code, refetch is skipped the first time because useFocusEffect calls our callback on mount in addition to screen focus.

Disable re-renders on out of focus Screens #

In 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.

This 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.

 1import React from 'react'
 2import { NotifyOnChangeProps } from '@tanstack/query-core'
 3import { useFocusEffect } from '@react-navigation/native'
 4
 5export function useFocusNotifyOnChangeProps(
 6  notifyOnChangeProps?: NotifyOnChangeProps,
 7) {
 8  const focusedRef = React.useRef(true)
 9
10  useFocusEffect(
11    React.useCallback(() => {
12      focusedRef.current = true
13
14      return () => {
15        focusedRef.current = false
16      }
17    }, []),
18  )
19
20  return () => {
21    if (!focusedRef.current) {
22      return []
23    }
24
25    if (typeof notifyOnChangeProps === 'function') {
26      return notifyOnChangeProps()
27    }
28
29    return notifyOnChangeProps
30  }
31}

In the above code, useFocusEffect is used to change the value of a reference that the callback will use as a condition.

The argument is wrapped in a reference to also guarantee that the returned callback always keeps the same reference.

Example usage:

 1function MyComponent() {
 2  const notifyOnChangeProps = useFocusNotifyOnChangeProps()
 3
 4  const { dataUpdatedAt } = useQuery({
 5    queryKey: ['myKey'],
 6    queryFn: async () => {
 7      const response = await fetch(
 8        'https://api.github.com/repos/tannerlinsley/react-query',
 9      )
10      return response.json()
11    },
12    notifyOnChangeProps,
13  })
14
15  return <Text>DataUpdatedAt: {dataUpdatedAt}</Text>
16}

Disable queries on out of focus screens #

Enabled 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.

 1import React from 'react'
 2import { useFocusEffect } from '@react-navigation/native'
 3
 4export function useQueryFocusAware(notifyOnChangeProps?: NotifyOnChangeProps) {
 5  const focusedRef = React.useRef(true)
 6
 7  useFocusEffect(
 8    React.useCallback(() => {
 9      focusedRef.current = true
10
11      return () => {
12        focusedRef.current = false
13      }
14    }, []),
15  )
16
17  return () => focusRef.current
18
19  useQuery({
20    queryKey: ['key'],
21    queryFn: () => fetch(...),
22    enabled: () => focusedRef.current,
23  })
24}