Course contentsShow
← React
Lesson 570 of 2,39616. useEffect for Data FetchingFree lesson

Handling Fetch Errors

Catch network errors and API failures, storing them in state to display meaningful error messages to users.

Handling Fetch Errors

You'll learn how to catch network errors and API failures, then display helpful error messages to your users instead of leaving them with a broken UI.

The Problem with Ignoring Errors

When you fetch data in useEffect, things can go wrong: the network might be down, the API might return an error status, or the server might be unreachable. If you don't handle these failures, your users see nothing—no data and no explanation. It's like ordering food and never hearing back whether your order succeeded or failed.

Storing Errors in State

Just like you manage loading state, you need to track error state:

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  fetch('https://api.example.com/users')
    .then(response => {
      if (!response.ok) {
        throw new Error('Failed to fetch users');
      }
      return response.json();
    })
    .then(data => {
      setData(data);
      setLoading(false);
    })
    .catch(err => {
      setError(err.message);
      setLoading(false);
    });
}, []);

Displaying Error Messages

Now you can show meaningful feedback:

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return <div>{/* render your data */}</div>;

The .catch() block captures both network failures (can't reach the server) and thrown errors (bad response status). You convert the error into a user-friendly message and store it in state, which triggers a re-render showing the error UI.

Key Takeaway: Always handle fetch errors by catching them and storing error messages in state—this transforms silent failures into clear feedback that helps users understand what went wrong.