Managing API Requests with Axios and React Query in React Native
Most React Native apps retrieve data from a backend. A good API layer should handle slow connections, loading and error states, caching, and refreshing data after a change—without copying the same useEffect logic into every screen.
Axios is an HTTP client. TanStack Query (often called React Query) manages the lifecycle of server data. They solve different problems and work well together.
This example uses TypeScript and a simple tasks API. Replace the endpoint and data shapes with your own service.
Install the libraries
npm install axios @tanstack/react-query
1. Create a small Axios client
import axios from 'axios';
export const api = axios.create({
baseURL: 'https://api.example.com', // Replace with your API URL
timeout: 15000,
});
Keep the base URL in configuration for real projects. If your API needs authentication, attach an access token in one place (for example, a request interceptor), and never put refresh tokens in logs or URL query parameters.
2. Define a typed request
import { api } from './client';
export type Task = {
id: string;
title: string;
completed: boolean;
};
export async function getTasks(): Promise<Task[]> {
const response = await api.get<Task[]>('/tasks');
return response.data;
}
export async function completeTask(id: string): Promise<void> {
await api.patch(`/tasks/${encodeURIComponent(id)}`, {
completed: true,
});
}
TypeScript describes the response you expect; it does not validate untrusted API data at runtime. Add schema validation if the API contract is not controlled by your team.
3. Configure QueryClient once
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { TasksScreen } from './src/screens/TasksScreen';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 1,
},
},
});
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<TasksScreen />
</QueryClientProvider>
);
}
staleTime controls how long fetched data is considered fresh. A fresh query is not automatically refetched just because a component renders again.
4. Fetch and render the tasks
import React from 'react';
import { ActivityIndicator, Button, FlatList, Text, View } from 'react-native';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { completeTask, getTasks } from '../api/tasks';
export function TasksScreen() {
const queryClient = useQueryClient();
const tasksQuery = useQuery({
queryKey: ['tasks'],
queryFn: getTasks,
});
const completeMutation = useMutation({
mutationFn: completeTask,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['tasks'] }),
});
if (tasksQuery.isPending) return <ActivityIndicator accessibilityLabel="Loading tasks" />;
if (tasksQuery.isError) {
return (
<View>
<Text>Could not load tasks.</Text>
<Button title="Retry" onPress={() => tasksQuery.refetch()} />
</View>
);
}
return (
<FlatList
data={tasksQuery.data}
keyExtractor={(task) => task.id}
refreshing={tasksQuery.isRefetching}
onRefresh={() => tasksQuery.refetch()}
renderItem={({ item }) => (
<View style={{ padding: 12 }}>
<Text>{item.title}</Text>
<Button
title={item.completed ? 'Completed' : 'Mark complete'}
disabled={item.completed || completeMutation.isPending}
onPress={() => completeMutation.mutate(item.id)}
/>
</View>
)}
/>
);
}
After a successful mutation, invalidating ['tasks'] marks the query stale and normally refetches it while it is active. This avoids manually editing the same list state in several screens.
For a production mutation, show feedback when completeMutation.isError is true and consider disabling only the affected row rather than every button.
React Native-specific considerations
Unlike a browser, React Native does not automatically provide all web focus and connectivity events to TanStack Query. For reconnect refetching and app-foreground refresh, integrate onlineManager with your connectivity library and focusManager with AppState, following the official React Native guide.
Be deliberate about credentials: avoid persisting sensitive API responses to disk without a threat model, and clear or isolate the query cache when a user signs out or switches accounts.
When should you use this combination?
Use Axios plus TanStack Query when multiple screens depend on server data, mutations must refresh related views, or retry/caching logic would otherwise be duplicated. If your app makes only one or two requests, fetch and a lightweight hook may be sufficient.