../courses.php
React
REACT108
90
Data Loading
Fetch data and show loading, success, and error states.
How does a React component load data from outside itself?
A React component can load data inside an effect, store the result in state, and render different interface states while loading succeeds or fails.
Real React apps do not only display hard-coded data.
They often load lessons, products, users, posts, settings, or dashboard data from an API.
Data loading needs more than one state. The app must know whether it is loading, whether it has data, and whether something went wrong.
A good React component does not pretend data appears instantly.
It shows a loading message, handles errors, and then renders the real data.
Loading lesson data
import { useEffect, useState } from "react";
function LessonList() {
const [lessons, setLessons] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function loadLessons() {
try {
const response = await fetch("/api/lessons.json");
if (!response.ok) {
throw new Error("Could not load lessons.");
}
const data = await response.json();
setLessons(data);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
loadLessons();
}, []);
if (loading) {
return <p>Loading lessons...</p>;
}
if (error) {
return <p>{error}</p>;
}
return (
<ul>
{lessons.map((lesson) => (
<li key={lesson.id}>
{lesson.title}
</li>
))}
</ul>
);
}
lessons stores the loaded data.
loading tracks whether the request is still running.
error stores an error message if the request fails.
fetch() requests data from the server.
finally runs after success or failure and stops the loading state.
Real data
React apps often render data from servers, APIs, or files.
User feedback
A loading state tells the user the app is working.
Failure handling
An error state prevents the app from failing silently.
Data-driven UI
Once data is loaded into state, React can render it as lists, cards, tables, or forms.
Assuming the data is already there
return (
<ul>
{lessons.map((lesson) => (
<li>{lesson.title}</li>
))}
</ul>
);
Loading, error, success
if (loading) {
return <p>Loading...</p>;
}
if (error) {
return <p>{error}</p>;
}
return <LessonResults lessons={lessons} />;
Ask ChatGPT: "Does this React data-loading component handle loading, success, and error states clearly?" Then trace what the user sees at each stage.
Create state for data, loading, and error.
Use useEffect to load data.
Use try, catch, and finally.
Render a loading message first.
Render either an error message or a list of loaded records.
Forgetting the loading state.
Ignoring failed requests.
Assuming fetch() always returns usable data.
Rendering a list without stable keys.
Putting too much data-loading logic into a component that should be split later.
Load data in React with an effect, store the data in state, and show loading, error, and success interface states.
Login - Jit4All
Login
Welcome back to Jit4All