🎓 A1Learner
🔍
0 of 50 lessons completed

Showing a Loading State

A loading state is a short message that shows while data is still on its way. It tells the reader that the app is working, not broken.

A loading flag in state

const [loading, setLoading] = useState(true);

Showing the loading line

{loading && <p>Loading notes…</p>}

Clearing the flag after the fetch

fetch('/api/notes')
  .then(() => setLoading(false));

Example

import { useState } from 'react';

export default function App() {
  const [loading] = useState(true);

  return (
    <div>
      <h1>Notes</h1>
      {loading && <p>Loading notes…</p>}
    </div>
  );
}

Key points

  • A loading flag is a boolean in state, and it starts as true.
  • The fetch runs inside useEffect when the component first shows.
  • The fetch sets the flag to false when the data arrives.
  • Conditional rendering shows the loading line only while the flag is true.

In this example, the loading flag starts as true, so the first render shows the loading line. The list is not rendered yet, because the notes have not arrived. In the real app, a fetch inside useEffect sets the flag to false. The list then takes the loading line's place.

Note

The loading line is the first thing the reader sees, so keep it short.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the loading state show while the notes are still on their way?