← Back to Chapters

Error Handling & Loading in React Native

⚠️ Error Handling & Loading in React Native

? Quick Overview

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.

? Key Concepts

  • Loading state using useState
  • Error state handling with conditional rendering
  • Try/Catch for async operations
  • Graceful UI fallback

? Syntax / Theory

React Native commonly uses boolean states like loading and error to control UI rendering during asynchronous tasks such as API calls.

? View Code Example
// Basic state setup for loading and error
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);

? Code Example(s)

? View Code Example
// 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);
}
};

? Live Output / Explanation

What Happens?

  • Loader is shown while data is fetching
  • Error message appears if API fails
  • Data renders only after success

? Interactive Example

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...

? View Code Logic (React Native)
// 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>
);
}

? Use Cases

  • API-based mobile apps
  • Form submissions
  • Authentication flows
  • Real-time data loading

? Tips & Best Practices

  • Always show a loader for async tasks
  • Use meaningful error messages
  • Reset error state before retry

? Try It Yourself

  • Add retry button on error
  • Replace loader with skeleton UI
  • Simulate API failure using wrong URL