React Course
React
/
Beginner

Fetch API

Definition

The native browser API for making HTTP requests to servers to retrieve or save data.

Explain Like I'm New

Fetch is like a mail carrier built right into the browser. You give it an address (URL), and it goes out to the internet, picks up the package (JSON data), and brings it back to your React component.

Real World Example

Fetching a list of users from `https://jsonplaceholder.typicode.com/users` when a component mounts, and storing that array in a `useState` hook to map over and display.

Common Use Cases

  • Retrieving data from a backend REST API
  • Sending form data via POST requests

Interactive Example

import React, { useState, useEffect } from "react";

export default function FetchDemo() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => {
        if (!res.ok) throw new Error("Server responded with " + res.status);
        return res.json(); // Returns another promise!
      })
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) return <div className="text-red-500">Error: {error}</div>;

  return (
    <ul className="p-4 border">
      {data.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

Interview Questions

basic

  • Is Fetch specific to React?
  • Does `fetch()` return data immediately?

intermediate

  • Why do you have to call `.json()` on a fetch response?
  • Does `fetch` throw an error if the server returns a 404 or 500?

advanced

  • How do you abort a fetch request if a component unmounts?
  • Why does React 18 Strict Mode cause fetch in `useEffect` to run twice?

trick

  • If the user's internet disconnects, does fetch throw an error or return a status code?

Flash Cards

Question

Does fetch throw an error on a 404 or 500?

Click to reveal answer
Answer

No! Fetch only throws a rejected Promise if there is a network failure (like the user losing internet). If the server receives the request and replies with `404 Not Found`, fetch considers that a SUCCESSFUL network request. You must manually check `if (!res.ok) throw new Error("Bad status");`.

Question

Why do you have to call .json()?

Click to reveal answer
Answer

The initial fetch Promise resolves as soon as the HTTP headers are received. The actual body of the response might take longer to download. Calling `.json()` returns a SECOND Promise that reads the incoming stream to completion and parses it into JavaScript objects.

Question

Is fetch specific to React?

Click to reveal answer
Answer

No, it is a standard Web API built into all modern browsers. React simply uses it.