A common pattern for loading data:
- Keep
data,loadinganderrorin state. - Fetch inside
useEffect. - Render a loading message, an error, or the data.
Load data from an API.
✍️ 3 exercises + code challenge in this lessonA common pattern for loading data:
data, loading and error in state.useEffect.Mastering React Fetching Data helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>
<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users?_limit=5")
.then(res => {
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
})
.then(setUsers)
.catch(err => setError(err.message))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading users...</p>;
if (error) return <p style={{ color: "red" }}>Error: {error}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name} — {u.company.name}</li>)}
</ul>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Check what you learned in “React Fetching Data”.
Fetch inside an effect.
useEffect(() => {
(url).then(r => r.json()).then(setData);
}, []);
Which three pieces of state does a typical data-loading component keep?
Fetch https://jsonplaceholder.typicode.com/users/1 and render the user's name in an <h2>.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services