React-Query for React Native: Optimize Data Fetching, Caching & Performance (Part 2)

In part 1, we briefly introduced React Query, a powerful library for managing server state in React and React Native applications. React Query simplifies data fetching, caching, synchronization, and updating, providing a seamless way to handle asynchronous operations and maintain consistent UI states. Now, in part 2, we will delve into implementing React Query within an application and explain its architecture in detail. We’ll cover how React Query’s core components work together to optimize data management and enhance the overall performance and user experience of your app.

Installation

Step 1: Set Up Your React Native Project

If you don’t have a React Native project set up already, you can create one using npx react-native init (for a new project) or you can use expo for a simpler setup.

Using React Native CLI:

Using Expo CLI:

Step 2: Install Dependencies

You need to install @tanstack/react-query along with react-query‘s development tools (optional but recommended).

Recommendations

It is recommended to also use our ESLint Plugin Query to help you catch bugs and inconsistencies while you code. You can install it via:

Step 3: Set Up React Query in Your Project

Create a React Query Client:

First, create a query client in your project. You can do this in a separate file, for example: src/config/react-query.js.

Provide the Query Client to Your App:

Wrap your application’s root component with the QueryClientProvider to provide the query client to your entire app.

Step 4: Fetch Data Using React Query

Now you can use React Query to fetch and manage server state in your components.

Create a Fetch Function:

  1. Create a function to fetch data from an API. This function can be placed in a separate file, for example: src/api.js.
  1. Use the useQuery Hook:

Use the useQuery hook to fetch data and manage the loading and error states.

To use the useQuery hook, you must pass at least two parameters:

  • The first parameter is the query key, which is a string[] data type, used for re-fetching, caching, and sharing data between components.
  • The second parameter is a function typically used to call an API, which returns a promise used to resolve data or throw an error.
  • The rest parameter is the options.

useQuery returns necessary information such as data, isFetching, or isError. We then use this information to display appropriate information.

Here’s a diagram that visualizes the flow of data in our application:

  1. Integrate the Component:

Finally, integrate your Todos component into your app.

Step 5: Run Your Project

Run your project to see React Query in action.

Yeah, you have successfully integrated React Query into your React Native application. The query with the key [“todos”] has a cache time of 2 days, meaning the data will be stored in the cache for 2 days. When you enter this screen, the cached data will be displayed immediately. Additionally, the query’s data remains fresh for 4 hours. After 4 hours, the data is marked as stale and can be re-fetched if necessary.

React Query Architecture

Query Core:

QueryClient:

  • defaultOptions: The default configuration options for queries (e.g., gcTime, staleTime, retry, etc.) are held within the QueryClient.
  • QueryCache: This holds all queries, managing their states and providing functionalities like garbage collection.

Query: Represents individual queries, which hold the data and status of each query.

QueryObserver: Observes queries for changes and updates the React components accordingly.

QueryClientProvider:

  • Provides the QueryClient to the React component tree, making it accessible to hooks like useQuery.

Framework Specific (React Components)

useQuery:

  • This hook is used within React components to fetch and manage data. It creates QueryObserver instances to subscribe to the corresponding queries.
  • queryKey: Identifies queries uniquely, allowing them to be cached and managed efficiently.

Component:

  • The React component that uses the useQuery hook to fetch data and render it.

External Storage:

Persisters:

  • Syncs the QueryCache with external storage like localStorage. This is used to persist the cache beyond the lifecycle of the application, enabling data to be restored on subsequent application loads

How It Works:

Initialization:

  • The QueryClient is initialized with default options.
  • The QueryClientProvider makes the QueryClient available to the component tree.

Fetching Data:

  • When a component uses the useQuery hook with a queryKey, it creates a QueryObserver.
  • The QueryObserver subscribes to the corresponding query in the QueryCache.

Managing Query States:

  • The QueryCache holds multiple queries, each representing a different data fetch request.
  • The state of these queries (loading, success, error) is managed by the QueryClient.

Updating Components:

  • The QueryObserver informs the components of any changes in the query state, prompting re-renders as necessary.
  • This ensures that components always have the latest data without manually handling state updates.

External Storage:

  • The QueryCache can sync with external storage through Persisters, enabling the persistence of query data.
  • This is useful for restoring the cache when the app is reloaded, reducing unnecessary data fetching.

           Summary:

    • The QueryClient holds and manages the global state of all queries.
    • The QueryCache maintains individual queries and their states.
    • The QueryObserver links queries to components, updating them as query states change.
    • The useQuery hook is the primary way components fetch and use data, leveraging the QueryClient and QueryCache.
    • External storage can persist the cache, ensuring data is retained between sessions.

Summary:

This guide on integrating React Query into React Native applications covers setting up a project, installing necessary dependencies, creating and providing a query client, and using the useQuery hook to fetch and manage data. It emphasizes the advantages of React Query for complex data fetching scenarios, such as caching, real-time updates, and error handling. The document also explains the architecture of React Query, including components like QueryClient, QueryCache, and QueryObserver, and how they work together to manage query states and update components efficiently.

If you are interested in Part 1, you can read more information HERE.

 

Facebook Like Button