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 installcommand with the appropriate installation instruction of your preferred package
npm install -g expo-cli
- Create a New Expo Project: Now, create a new project using the Expo CLI:
expo init my-react-native-query-app
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
- Install Required Dependencies
npx expo install @react-native-community/netinfo
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)
})
})
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()
}, [])
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]),
)
}
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>
}
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
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)