Error handling and loading states are essential for building reliable React Native applications. They help manage network delays, API failures, and unexpected crashes while giving users clear feedback.
useStateReact Native commonly uses boolean states like loading and error to control UI rendering during asynchronous tasks such as API calls.
// Basic state setup for loading and error
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Fetching data with loading and error handling
const fetchUsers = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch("https://api.example.com/users");
const data = await response.json();
setUsers(data);
} catch (err) {
setError("Failed to load data");
} finally {
setLoading(false);
}
};
Click the buttons below to simulate an API call in a React Native app context. Watch how the UI state changes.
Tap a button to start fetch...
// Conditional UI rendering based on state
if (loading) {
return <ActivityIndicator size="large" />;
}
if (error) {
return (
<View>
<Text>{error}</Text>
<Button title="Retry" onPress={fetchData} />
</View>
);
}