Search code examples
react-nativeexporeact-querytanstackreact-query

React Query in Expo wont refetch


I'm building an Expo React Native app using Expo Navigation (Stack Navigator) and React Query. When navigating between screens (e.g., from Home to Test screen and back), I need to refetch data when returning to the previous screen. The problem is the component doesn't remount on navigation, hence the query function doesn't trigger/


Solution

  • The screen won't be remounted on back navigation as you have mentioned yourself, but it will be refocused. This is described in the official documentation of TanStack query. The provided solution makes use of the useFocusEffect hook of react-navigation.

    export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
      const firstTimeRef = React.useRef(true)
    
      useFocusEffect(
        React.useCallback(() => {
          if (firstTimeRef.current) {
            firstTimeRef.current = false
            return
          }
    
          refetch()
        }, [refetch]),
      )
    }
    

    In your screens, you need to call the above hook and provide the refetch function returned by useQuery.