Fetching and Managing Remote Data
9 min read
Modern mobile applications are rarely isolated islands; they rely on remote data to function. Whether you are building a social media feed, an e-commerce store, or a weather app, you need to know how to securely and efficiently ask servers for information and display it to your users.
In this guide, we will walk through the industry standards for fetching, displaying, and caching data in Expo and React Native.
1. Network Requests: Fetch API and Axios Basics 🌐
Definition: A network request is an HTTP message sent from your application to a remote server to retrieve, update, create, or delete data.
The Problem: By default, your app runs purely on the user's device and has no idea what is happening in the outside world. If you want to show a list of products, the app needs a mechanism to talk to a remote database to get that information over the internet.
The Solution: We use HTTP clients to send these requests. The two most common tools in the React Native industry are the native Fetch API and a third-party library called Axios.
Scenario: Imagine you are managing a restaurant (your app). You need fresh ingredients (data). You cannot grow them in the dining room. You have to call the supplier (the server) and ask them to deliver the ingredients (the request). You then wait for the delivery truck to arrive (the response) before you can cook the meal (render the screen).
The Built-in Way: Fetch API
The Fetch API is built directly into JavaScript. It allows you to make network requests and returns a Promise—a representation of a value that might be available now, later, or never.
const fetchProducts = async () => {
try {
// 1. Make the request
const response = await fetch('https://api.example.com/products');
// 2. Parse the response into JSON
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Failed to fetch products:", error);
}
};The Industry Standard: Axios
While fetch is great, axios is heavily favored in enterprise applications because it reduces boilerplate. It automatically converts responses to JSON, throws proper errors for bad HTTP statuses (like 404 or 500), and allows you to easily set base URLs and headers.
import axios from 'axios';
const fetchProducts = async () => {
try {
// Axios automatically parses the JSON for you!
const response = await axios.get('https://api.example.com/products');
console.log(response.data);
} catch (error) {
// Axios catches network errors AND server errors (like 500 Internal Server Error)
console.error("Failed to fetch products:", error.message);
}
};💡 Interesting Fact: Before fetch became the standard in 2015, developers had to use a tool called XMLHttpRequest. It was famously verbose, required multiple event listeners just to check if a request finished, and despite having "XML" in the name, it was mostly used to fetch JSON data!
2. Handling Loading States, Errors, and Empty Screens 🚦
Definition: UI States represent the different visual conditions of your application based on the status of the data being requested (Loading, Error, Empty, Success).
The Problem: The internet is not instantaneous and networks are unpredictable. If you request data and immediately try to render it, your app will crash because the data is undefined. Furthermore, if the user's Wi-Fi drops, the request will fail. If you don't handle these scenarios, the user is left staring at a frozen, blank screen wondering if your app is broken.
The Solution: We use React state variables to track exactly what phase the request is in, and render different components based on those variables.
Here is how you handle the core states every app needs:
import React, { useState, useEffect } from 'react';
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native';
export default function ProductScreen() {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const loadData = async () => {
try {
setIsLoading(true);
const response = await fetch('https://api.example.com/products');
if (!response.ok) throw new Error('Something went wrong!');
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false); // Always stops the loading spinner
}
};
loadData();
}, []);
// 1. Loading State
if (isLoading) {
return (
<View style={styles.center}>
<ActivityIndicator size="large" color="#0000ff" />
<Text>Loading your products...</Text>
</View>
);
}
// 2. Error State
if (error) {
return (
<View style={styles.center}>
<Text style={styles.errorText}>Oops: {error}</Text>
</View>
);
}
// 3. Empty State
if (data.length === 0) {
return (
<View style={styles.center}>
<Text>No products available right now. Check back later!</Text>
</View>
);
}
// 4. Success State
return (
<View style={styles.container}>
{data.map(item => (
<Text key={item.id}>{item.name}</Text>
))}
</View>
);
}
const styles = StyleSheet.create({
center: { flex: 1, justifyContent: 'center', alignItems: 'center' },
container: { flex: 1, padding: 20 },
errorText: { color: 'red', fontSize: 16 }
});3. Implementing Pull-to-Refresh and Infinite Scrolling 📜
Definition:
- Pull-to-Refresh: A touch gesture where the user drags the screen downward to trigger a manual data refresh.
- Infinite Scrolling: A UI pattern where new data is automatically fetched and appended to the bottom of a list as the user scrolls near the end.
The Problem: If a user is looking at a news feed, they need a way to check if there are new articles without restarting the app. At the same time, if your database has 10,000 articles, fetching and rendering all of them at once will consume massive amounts of memory. Doing so will effectively turn the user's phone into a very expensive pocket warmer and crash the app.
The Solution: Use React Native's FlatList component. It efficiently renders only the items currently visible on the screen. We can attach a RefreshControl prop for the pull-to-refresh gesture, and the onEndReached prop to trigger infinite scrolling.
import React, { useState } from 'react';
import { FlatList, Text, View, RefreshControl, StyleSheet, ActivityIndicator } from 'react-native';
export default function FeedScreen() {
const [data, setData] = useState([...Array(15).keys()]); // Dummy data
const [isRefreshing, setIsRefreshing] = useState(false);
const [isFetchingMore, setIsFetchingMore] = useState(false);
// Triggered when the user pulls the list down
const handleRefresh = async () => {
setIsRefreshing(true);
// Simulate a network request getting fresh top data
await new Promise(resolve => setTimeout(resolve, 1500));
setData([...Array(15).keys()]); // Reset list
setIsRefreshing(false);
};
// Triggered when the user reaches the bottom of the list
const handleLoadMore = async () => {
if (isFetchingMore) return; // Prevent duplicate requests
setIsFetchingMore(true);
// Simulate network request getting the next page
await new Promise(resolve => setTimeout(resolve, 1000));
const nextData = [...Array(10).keys()].map(i => i + data.length);
setData(prevData => [...prevData, ...nextData]);
setIsFetchingMore(false);
};
return (
<FlatList
data={data}
keyExtractor={(item) => item.toString()}
renderItem={({ item }) => (
<View style={styles.card}>
<Text>Post #{item}</Text>
</View>
)}
// ⬇️ Pull-to-Refresh Config
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />
}
// ⬇️ Infinite Scroll Config
onEndReached={handleLoadMore}
onEndReachedThreshold={0.5} // Trigger when user is halfway through the last screen of items
ListFooterComponent={
isFetchingMore ? <ActivityIndicator style={{ margin: 20 }} /> : null
}
/>
);
}
const styles = StyleSheet.create({
card: { padding: 20, borderBottomWidth: 1, borderColor: '#ccc' }
});4. Data Caching Strategies with React Query 🧠
Definition: Data caching is the process of storing data in a temporary, quickly accessible memory location so that future requests for that same data can be served much faster.
The Problem: Managing data fetching with useEffect and useState (as we did in Section 2) is incredibly tedious. You have to manually track loading states, handle errors, and prevent duplicate requests. If a user navigates to a profile screen, goes back to the home screen, and clicks the profile again, the app will blindly re-fetch the data and show a loading spinner every single time. This wastes network data and creates a sluggish user experience.
The Solution: Use TanStack Query (formerly known as React Query). It automatically handles caching, dedupes multiple requests for the same data, and manages your loading/error states out of the box.
Scenario: Imagine a librarian. When someone asks for a specific history book, the librarian goes to the basement, finds it, and brings it up. Instead of immediately returning the book to the basement when the person is done, the librarian keeps it on the front desk (the cache). When the next person asks for the exact same book five minutes later, the librarian simply hands it over instantly. Under the hood, TanStack Query uses a strategy called stale-while-revalidate—it hands you the cached book immediately, but quietly sends an assistant to the basement to check if a newer edition just arrived.
Installation
To get started, install the library:
npm install @tanstack/react-querySetup
You need to wrap your app in a QueryClientProvider. If you are using Expo Router, you usually do this in your app/_layout.tsx file (or App.js for standard React Native).
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// Create a client manager
const queryClient = new QueryClient();
export default function RootLayout() {
return (
<QueryClientProvider client={queryClient}>
<YourAppComponents />
</QueryClientProvider>
);
}Usage in a Screen
Once set up, you replace all your useEffect and useState logic with a single useQuery hook.
import { Text, View, ActivityIndicator } from 'react-native';
import { useQuery } from '@tanstack/react-query';
const fetchUser = async () => {
const response = await fetch('https://api.example.com/user/1');
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
};
export default function UserProfile() {
const { data, isLoading, error } = useQuery({
queryKey: ['user', 1], // The unique ID for this cache
queryFn: fetchUser, // The function that does the fetching
});
if (isLoading) return <ActivityIndicator />;
if (error) return <Text>Error: {error.message}</Text>;
return (
<View>
<Text>Welcome, {data.name}!</Text>
</View>
);
}😂 Humorous observation: React Query is so good at its job that once you start using it, looking back at your old useEffect fetch code will make you physically wince.
By assigning a queryKey (like ['user', 1]), TanStack Query remembers the result of this fetch. If you navigate to another screen and come back, useQuery will instantly return the cached data while checking the server in the background for any updates.
🔗 References & Further Reading
Challenge
You are tasked with building a UserList component for a React Native application. This component will fetch a list of users from a remote API, display them, and allow the user to refresh the list.
Your implementation must adhere to the following requirements:
- Use
Axiosto perform the GET request tohttps://jsonplaceholder.typicode.com/users. - Manage the data fetching, caching, and state management using the
useQueryhook fromTanStack Query. The query key for this data should be['users']. - The component must handle three distinct states:
- Loading: While the data is being fetched for the first time, display a built-in
ActivityIndicator. - Error: If the request fails, display a
Textcomponent with the message "Failed to fetch users." - Success: When the data is successfully fetched, display it in a
FlatList.
- Loading: While the data is being fetched for the first time, display a built-in
- The
FlatListshould render thenameof each user. Use the user'sidas the key for each item. - Implement a pull-to-refresh functionality on the
FlatList. When the user pulls down, the data should be refetched.
Expected result
Your final code should be a complete React Native component named UserList.
The solution must contain the following:
- An
asyncfunctionfetchUsersthat usesaxios.get(API_URL)to fetch data and returnsresponse.data. - A call to the
useQueryhook inside theUserListcomponent, like so:useQuery({ queryKey: ['users'], queryFn: fetchUsers }). - The
data,isLoading,isError, andrefetchproperties are destructured from the result ofuseQuery. - The
onRefreshfunction should be defined and it must call therefetchfunction. - Conditional rendering logic:
- The first
ifblock checksisLoadingto render theActivityIndicator. - The second
ifblock checksisErrorto render the error message.
- The first
- The
FlatListcomponent must be correctly configured:dataprop is set to thedataobject returned byuseQuery.refreshControlprop is passed aRefreshControlcomponent.- The
refreshingprop ofRefreshControlis set toisLoading. - The
onRefreshprop ofRefreshControlis set to theonRefreshhandler function you created.