Skip to content

Data Fetching

From the beginning of React, the community has been building a rich ecosystem of tools and libraries that help you build your applications. One of the most important parts of this ecosystem is the ability to fetch data from a server and display it in your application.

While there are numerous options available for fetching data in React and React Native, the community has recently been gravitating towards adopting React Query as the go-to solution. The reason for this trend is due to React Query’s simplicity, flexibility, and tone of features that it provides out of the box.

What is react-query?

React-query It is a very powerful library that helps you manage your data fetching, caching, invalidating, and even implementing optimistic UI in a very simple way.

react-query offers hooks that simplify the process of fetching and updating data in your app. You can use pre-built hooks like useQuery and useMutation, or create your own custom hooks based on them. This makes it easier for developers to manage data and build more efficient applications.

Using react-query-kit & axios

As the starter is designed to save you time and effort, we already have installed react-query and Axios and configured them for you.

The src/api folder contains all the fetching logic, with a common sub-folder that holds a client, queryClient, and several utility functions specifically designed to work with react-query.

Because we’re using Axios as the client, we can leverage all its advanced features, including interceptors, request cancellation, and more. For additional information on Axios, you can check out their website here.

To make writing queries and mutation even easier we are using react-query-kit, a simple toolkit that makes ReactQuery reusable and type-safe with less boilerplate.

Data Fetching Use Cases

Suppose you’re building a blog app and need to add the following features:

  • A Feed Screen that displays all posts
  • A Post Screen that shows the details of a single post
  • A Screen to create a new post

To get started, create a new folder named posts within src/api. This folder will hold all the post-related logic. You can apply this same concept to any other entities, such as users, within your application.

Feed Screen

The feed screen will show all the posts available in the app. To achieve this, we need to create a hook called usePosts that will fetch the posts and display them as a list.

Here are the steps to create the usePosts hook:

  1. Inside the src/api/posts folder, create a new file called use-posts.ts.
  2. Define the type for your Response and Variables if required, to ensure that you receive the correct data from the server. For instance, you could create a Post type for the posts.
  3. Use the createQuery function from react-query-kit library to create a query hook that will fetch the data from the server. We’ll name it usePosts hook.

Below is the complete code for the use-posts.ts file:

import type { AxiosError } from 'axios';
import { createQuery } from 'react-query-kit';
import { client } from '../common';
import type { Post } from './types';
type Response = Post[];
type Variables = void; // as react-query-kit is strongly typed, we need to specify the type of the variables as void in case we don't need them
export const usePosts = createQuery<Response, Variables, AxiosError>({
primaryKey: 'posts', // we recommend using endpoint base url as primaryKey
queryFn: ({ queryKey: [primaryKey] }) => {
// in case if variables is needed, we can use destructuring to get it from queryKey array like this: ({ queryKey: [primaryKey, variables] })
// primaryKey is 'posts' in this case
return client.get(`${primaryKey}`).then((response) =>;

the createQuery function accept an object with the following: queryKey, queryFn and options. Read more about (createQuery)[]

Now that we have created our custom hook, we can use it in our app to display a list of posts. Follow the steps below to achieve this:

  1. Create a new screen in your app and name it Posts.
  2. Import and use the usePosts hook we created earlier to fetch the list of posts.
  3. Use the fetched data to display a list of posts.
import { useNavigation } from '@react-navigation/native';
import { FlashList } from '@shopify/flash-list';
import React from 'react';
import type { Post } from '@/api';
import { usePosts } from '@/api';
import { EmptyList, FocusAwareStatusBar, Text, View } from '@/ui';
import { Card } from './card';
export const Feed = () => {
const { data, isLoading, isError } = usePosts();
const { navigate } = useNavigation();
const renderItem = React.useCallback(
({ item }: { item: Post }) => (
<Card {...item} onPress={() => navigate('Post', { id: })} />
if (isError) {
return (
<Text> Error Loading data </Text>
return (
<View className="flex-1 ">
<FocusAwareStatusBar />
keyExtractor={(_, index) => `item-${index}`}
ListEmptyComponent={<EmptyList isLoading={isLoading} />}

As you can see in the code above, we use the usePosts hook to fetch data and handle the loading state. This allows us to display a loading indicator while the data is being fetched, and then display the list of posts once the data is ready.

In the same example above we also show an error message if the request fails.

Post Screen

The post screen will display the details of a single post. To fetch and display the post, we will create a new hook called usePost.

We can use the same steps we used earlier to create the usePosts hook. The only difference is that we will use the id of the post as a variable to fetch the specific post.

Below is the complete code for the use-post.ts file:

import type { AxiosError } from 'axios';
import { createQuery } from 'react-query-kit';
import { client } from '../common';
import type { Post } from './types';
type Variables = { id: number };
type Response = Post;
export const usePost = createQuery<Response, Variables, AxiosError>({
primaryKey: 'posts',
queryFn: ({ queryKey: [primaryKey, variables] }) => {
return client
.then((response) =>;

Now our hook is ready to be used in our post details screen:

import { useRoute } from '@react-navigation/native';
import * as React from 'react';
import { usePost } from '@/api';
import type { RouteProp } from '@/navigation/types';
import { ActivityIndicator, FocusAwareStatusBar, Text, View } from '@/ui';
export const Post = () => {
const { params } = useRoute<RouteProp<'Post'>>();
const { data, isLoading, isError } = usePost({
variables: { id: },
if (isLoading) {
return (
<View className="flex-1 justify-center">
<ActivityIndicator />
if (isError) {
return (
<View className="flex-1 justify-center">
<FocusAwareStatusBar />
<Text variant="md" className="text-center">
Error loading post
return (
<View className="flex-1 ">
<FocusAwareStatusBar />
<Text variant="h2">{data.title}</Text>
<Text variant="md">{data.body} </Text>

Add new post

To add a new post, we can use the createMutation function from the react-query-kit library.

Here are the steps to create the useAddPost hook:

  1. Create a new file called use-add-post.ts inside the src/api/posts folder.
  2. Define a type for your Variables and Response to ensure that you are sending the correct data to the server.
  3. Use the createMutation function from react-query-kit library to create a mutation hook that will send the data to the server. We’ll name this hook useAddPost.

Here is the complete code for the use-add-post.ts file:

import type { AxiosError } from 'axios';
import { createMutation } from 'react-query-kit';
import { client } from '../common';
import type { Post } from './types';
type Variables = { title: string; body: string; userId: number };
type Response = Post;
export const useAddPost = createMutation<Response, Variables, AxiosError>({
mutationFn: async (variables) =>
url: 'posts/add',
method: 'POST',
data: variables,
}).then((response) =>,

Now that we have our mutation hook ready. Let’s create a new screen called AddPost and use data from useAddPost hook to create a new post:

Exactly the same way we did in form section while creating a login form, we will follow the same approach to create a from to create a new post.

  1. Create the schema for the new form using Zod
  2. Create the form using react-hook-form
  3. Get mutate function from useAddPost hook and call it when the form is submitted
  4. You can use the isLoading state to display a loading indicator while the data is being sent to the server and then redirect the user to the feed screen on success.
import { zodResolver } from '@hookform/resolvers/zod';
import * as React from 'react';
import { useForm } from 'react-hook-form';
import { showMessage } from 'react-native-flash-message';
import { z } from 'zod';
import { useAddPost } from '@/api';
import { Button, ControlledInput, showErrorMessage, View } from '@/ui';
const schema = z.object({
title: z.string().min(10),
body: z.string().min(120),
type FormType = z.infer<typeof schema>;
export const AddPost = () => {
const { control, handleSubmit } = useForm<FormType>({
resolver: zodResolver(schema),
const { mutate: addPost, isLoading } = useAddPost();
const onSubmit = (data: FormType) => {
{, userId: 1 },
onSuccess: () => {
message: 'Post added successfully',
type: 'success',
// here you can navigate to the post list and refresh the list data
onError: () => {
showErrorMessage('Error adding post');
return (
<View className="flex-1 p-4 ">
label="Add Post"

Create API Hooks with Vs Code Snippets

Maybe you mentioned that creating a new query or mutation hook looks the same every time and you are right. That is why we created a set of vscode snippets to help you create your hooks in no time.

  • useq : Create a new query hook


  • useqp : Create a new query hook with params

  • useiq : Create a new infinite query hook

  • usem : Create a new mutation hook