In React Native applications, handling empty lists and loading states is essential for providing a smooth user experience. Instead of showing a blank screen, developers display loaders, placeholders, or friendly messages while data is being fetched or when no data is available.
React Native provides the FlatList component to render scrollable lists efficiently. It supports a special prop called ListEmptyComponent which is rendered when the data array is empty.
// FlatList with loading and empty state handling
import React, { useEffect, useState } from "react";
import { View, Text, FlatList, ActivityIndicator } from "react-native";
export default function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Simulate network request
setTimeout(() => {
setData([]); // Or data from API
setLoading(false);
}, 2000);
}, []);
if (loading) {
return ;
}
return (
index.toString()}
ListEmptyComponent={No data available }
renderItem={({ item }) => {item.name} }
/>
);
}
Initially, a loading spinner is shown. After the data fetch completes, the list checks if the data array is empty. Since it is empty, a friendly message is displayed instead of a blank screen.
Use the controls below to simulate how a Mobile App reacts to data fetching, receiving data, or receiving an empty result.