🎓 A1Learner
🔍
0 of 50 lessons completed

Loading and Error States

Loading and error states tell the reader what is happening. A loading state shows while data travels, and an error state shows when the request fails.

Three states

The three state values cover data, loading, and error.

const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
return <p>{loading ? 'Loading...' : 'Done.'}</p>;

Show the error

The paragraph shows only when error holds a message.

const [error, setError] = useState('Server is down.');
return <div>{error && <p>{error}</p>}</div>;

Example

import { useState, useEffect } from 'react';

export default function App() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://example.com/api/users')
      .then((response) => response.json())
      .then((data) => {
        setUsers(data);
        setLoading(false);
      })
      .catch(() => {
        setError('Could not load users.');
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>{error}</p>;
  }
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Key points

  • A loading state value starts as true.
  • The loading state value turns false when the data arrives.
  • An error state value starts empty and holds a message when the request fails.
  • The catch method runs when the request fails.
  • The component shows one message at a time.

In this example, the users state value starts empty. The loading state value starts as true. The error state value starts empty. The effect asks the server for users after mount. The first render shows Loading because the effect has not run yet. When the data arrives, loading turns false and the list shows. When the request fails, catch stores the message and the error shows.

Note

The error message comes from the failed request, not from the data.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What shows while data is still travelling?