DEV Community

Cover image for Set up React Query on an Expo Project
Ibukun Demehin
Ibukun Demehin

Posted on

Set up React Query on an Expo Project

There is a good chance that you will need to interact with an external API to receive and send data, and with React Query, it makes the process easy and lets us focus on the data more than the logic of getting the data. In this blog post, we'll guide you through the steps to set up a React Native project using Expo and integrate it with React Query, ensuring you can manage your API requests efficiently.

Step 1: Set Up Your Expo Project

The first step is to create a new Expo project. Expo is a framework and a platform for universal React applications, and it simplifies the process of developing and deploying React Native apps.

If you have existing project then you can skip this step and move on to step 2

  • Install Expo CLI: If you haven't already, you need to install the Expo CLI. You can do this globally using npm:

You could use any other package manager you are comfortable with at this time, just replace the npm install command with the appropriate installation instruction of your preferred package

npm install -g expo-cli
Enter fullscreen mode Exit fullscreen mode
  • Create a New Expo Project: Now, create a new project using the Expo CLI:
expo init my-react-native-query-app
Enter fullscreen mode Exit fullscreen mode

Choose a template based on your preference.

Step 2: Install React Query & Required Dependencies

React Query is a powerful tool for managing server state in your React and React Native applications. It provides hooks to fetch, cache, and sync your data without requiring global state management.

  • Install React Query
npm install @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode
  • Install Required Dependencies
npx expo install @react-native-community/netinfo
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Helper Functions for the project

We will create three functions that we will need in this project. The functions will be custom hooks and we can have it saved in a subfolder called hooks at the root directory.

  • Create useAppState.ts function
import NetInfo from '@react-native-community/netinfo'
import { onlineManager } from '@tanstack/react-query'

onlineManager.setEventListener((setOnline) => {
  return NetInfo.addEventListener((state) => {
    setOnline(!!state.isConnected)
  })
})
Enter fullscreen mode Exit fullscreen mode

This function will perform auto-refetch anytime your reconnect your app to a working internet if you went offline

  • Create UseOnlineManager.ts function
import { useEffect } from 'react'
import { AppState, Platform } from 'react-native'
import type { AppStateStatus } from 'react-native'
import { focusManager } from '@tanstack/react-query'

function onAppStateChange(status: AppStateStatus) {
  if (Platform.OS !== 'web') {
    focusManager.setFocused(status === 'active')
  }
}

useEffect(() => {
  const subscription = AppState.addEventListener('change', onAppStateChange)

  return () => subscription.remove()
}, [])
Enter fullscreen mode Exit fullscreen mode

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

  • Create useRefreshOnFocus.ts function
import React from 'react'
import { useFocusEffect } from '@react-navigation/native'

export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
  const firstTimeRef = React.useRef(true)

  useFocusEffect(
    React.useCallback(() => {
      if (firstTimeRef.current) {
        firstTimeRef.current = false
        return
      }

      refetch()
    }, [refetch]),
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

Step 4: Implement all the functions in your root file

Whatever your main route file might be based on how your project is set up, you can add the below code right there

import {
  QueryClient,
  QueryClientProvider,
  focusManager,
} from "@tanstack/react-query";
import { AppStateStatus, Platform } from "react-native";
import { useOnlineManager } from "@/hooks/query/useOnlineManager";
import { useAppState } from "@/hooks/query/useAppState";

export default function RootLayout() {
  function onAppStateChange(status: AppStateStatus) {
    if (Platform.OS !== "web") {
      focusManager.setFocused(status === "active");
    }
  }

  const queryClient = new QueryClient({
    defaultOptions: { queries: { retry: 2 } },
  });

  useOnlineManager();

  useAppState(onAppStateChange);
  <QueryClientProvider client={queryClient}>
    {Rest of your project}
  </QueryClientProvider>
}
Enter fullscreen mode Exit fullscreen mode

With this, you'll be able to use react query in your mobile development just the same way you use it in web

  • Start the Development Server: In your terminal, navigate to the folder that Expo created with all of the boilerplate set-up and run
expo start
Enter fullscreen mode Exit fullscreen mode

Expo projects can be built quickly using Expo Go app that can be downloaded on your phone but it is encouraged to build a development app instead from the beginning of your project. You can see the docs on how to do that.

Conclusion

By setting up an Expo React Native project with React Query, you can streamline the process of managing server state and interacting with APIs. React Query's powerful features, such as caching, background updates, and synchronization, allow you to focus on what truly mattersβ€”the data, not the data-fetching logic.

HAPPY CODING πŸ‘¨πŸΌβ€πŸ’» πŸ‘©πŸ»β€πŸ’» πŸ’»

Top comments (0)