React Query helps you get data from the internet easily and keeps it fresh. It saves you from writing lots of code to handle loading and errors.
0
0
React Query for data fetching in React Native
Introduction
When you want to show a list of items from a website or server in your app.
When you need to update data automatically without making the user refresh.
When you want to handle loading and error messages simply.
When you want to cache data so your app feels faster.
When you want to keep data synced in the background.
Syntax
React Native
import { useQuery } from '@tanstack/react-query'; const { data, error, isLoading } = useQuery({ queryKey: ['key'], queryFn: async () => { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); } });
useQuery is a hook that fetches and manages data.
queryKey is a unique name for the data you want to fetch.
Examples
Fetches a list of todos from a public API.
React Native
const { data, isLoading } = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('https://jsonplaceholder.typicode.com/todos').then(res => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
});Fetches data for a specific user using a dynamic key.
React Native
const { data, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`https://api.example.com/user/${userId}`).then(res => {
if (!res.ok) {
throw new Error('Network response was not ok');
}
return res.json();
})
});Sample App
This app fetches a list of todos from the internet and shows them in a scrollable list. It shows a loading spinner while waiting and an error message if something goes wrong.
React Native
import React from 'react'; import { View, Text, ActivityIndicator, FlatList } from 'react-native'; import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; const queryClient = new QueryClient(); function Todos() { const { data, error, isLoading } = useQuery({ queryKey: ['todos'], queryFn: () => fetch('https://jsonplaceholder.typicode.com/todos').then(res => { if (!res.ok) { throw new Error('Network response was not ok'); } return res.json(); }) }); if (isLoading) return <ActivityIndicator size="large" />; if (error) return <Text>Error loading todos.</Text>; return ( <FlatList data={data} keyExtractor={item => item.id.toString()} renderItem={({ item }) => <Text>{item.title}</Text>} /> ); } export default function App() { return ( <QueryClientProvider client={queryClient}> <View style={{ flex: 1, padding: 20, marginTop: 50 }}> <Text style={{ fontSize: 24, marginBottom: 10 }}>Todo List</Text> <Todos /> </View> </QueryClientProvider> ); }
OutputSuccess
Important Notes
React Query automatically caches data to make your app faster.
It handles loading and error states so you don't have to write extra code.
Always wrap your app with QueryClientProvider to use React Query.
Summary
React Query makes fetching and managing server data easy in React Native apps.
Use useQuery with a unique key and a function that fetches data.
It helps with loading, errors, caching, and updating data automatically.