React Fetching Data

Load data from an API.

✍️ 3 exercises + code challenge in this lesson

A common pattern for loading data:

  1. Keep data, loading and error in state.
  2. Fetch inside useEffect.
  3. Render a loading message, an error, or the data.
In larger apps, libraries like TanStack Query or framework features (Next.js) handle caching, retries and loading states for you.

Key Takeaways: React Fetching Data

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.

React Fetching Data Code Example

React
<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>
Free sign-in required · Google login available

React Fetching Data Practice Exercises

Check what you learned in “React Fetching Data”.

/ 3 solved
Fill in the blank

Fetch inside an effect.

useEffect(() => {
  (url).then(r => r.json()).then(setData);
}, []);
✓ Correct! Not quite. Try again.
Multiple choice

Which three pieces of state does a typical data-loading component keep?

✓ Correct! Not quite. Try again.
Code challenge

Fetch https://jsonplaceholder.typicode.com/users/1 and render the user's name in an <h2>.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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