How to Set Up an Expo React Native Project with React Query

Ibukun demehinIbukun demehin
3 min read

Interacting with external APIs is often essential, and React Query simplifies this by allowing you to focus on the data rather than the complexity of fetching it. This guide will walk you through setting up a React Native project using Expo and integrating it with React Query.

Step 1: Set Up Your Expo Project

To get started, install Expo CLI and create a new project. If you already have a project, skip to the next step.

  • Install Expo CLI:

      npm install -g expo-cli
    
  • Create a New Project:

      expo init my-react-native-query-app
    

    Choose a template based on your needs.

Step 2: Install React Query & Dependencies

React Query is powerful for managing server state in your React Native apps.

  • Install React Query:

      npm install @tanstack/react-query
    
  • Install Additional Dependencies:

      npx expo install @react-native-community/netinfo
    

Step 3: Create Helper Functions

Create three custom hooks in a hooks folder at the root of your project.

  1. useAppState.ts:

     import NetInfo from '@react-native-community/netinfo';
     import { onlineManager } from '@tanstack/react-query';
    
     onlineManager.setEventListener((setOnline) => {
       return NetInfo.addEventListener((state) => {
         setOnline(!!state.isConnected);
       });
     });
    

    This enables auto-refetch when the app reconnects to the internet.

  2. UseOnlineManager.ts:

     import { useEffect } from 'react';
     import { AppState, Platform } 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();
     }, []);
    

    This updates the app state when the app is active.

  3. useRefreshOnFocus.ts:

     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]),
       );
     }
    

    This custom hook triggers a refetch when the screen is focused.

Step 4: Implement the Functions in Your Root File

In your main route file, set up the following:

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);

  return (
    <QueryClientProvider client={queryClient}>
      {Rest of your project}
    </QueryClientProvider>
  );
}

Step 5: Start Your Development Server

Navigate to your project directory and start the Expo development server:

expo start

Expo allows quick testing via the Expo Go app or by building a development app. For more details on creating a development build, refer to Expo's documentation.

Conclusion

Setting up an Expo React Native project with React Query simplifies state management and API interactions. By leveraging React Query's powerful features, such as caching and background updates, you can focus more on your data and less on the intricacies of fetching it.

Happy Coding! ๐Ÿ‘จ๐Ÿผโ€๐Ÿ’ป ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป ๐Ÿ’ป

0
Subscribe to my newsletter

Read articles from Ibukun demehin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ibukun demehin
Ibukun demehin

I am a skilled and passionate React frontend developer with a strong foundation in building captivating user interfaces and seamless web experiences. With a meticulous eye for detail and a deep understanding of modern web development principles, I thrive in creating elegant, responsive, and intuitive designs that enhance user engagement. Throughout my career, I have honed my expertise in React, utilizing its powerful components and state management to craft dynamic and interactive user interfaces. From designing pixel-perfect layouts to implementing smooth transitions and animations, I possess a knack for transforming complex concepts into visually appealing and user-friendly solutions. In addition to React, I am well-versed in HTML, CSS, and JavaScript, allowing me to build cohesive and well-structured front-end architectures. I am also experienced in leveraging various libraries and frameworks, such as Redux, TypeScript, and Material-UI, to optimize development processes and deliver high-quality code.