MyInternships.in

Data Fetching & APIs

React Fetching Data with useEffect

The classic way to load data in React is to call fetch inside useEffect, store the result in state, and render from that state. You need three pieces of state — data, loading and error — to cover every outcome.


What is Fetching Data with useEffect in React?

The classic way to load data in React is to call fetch inside useEffect, store the result in state, and render from that state. You need three pieces of state — data, loading and error — to cover every outcome.

Why Fetching Data with useEffect matters

Almost every real screen shows server data. Handling loading and error explicitly is what separates a demo from something users can trust.

Fetching Data with useEffect example

A complete fetch with all three states
JSX
function JobList() {
  const [jobs, setJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    async function load() {
      try {
        setLoading(true);
        const res = await fetch('/api/jobs', { signal: controller.signal });
        if (!res.ok) throw new Error(`Request failed: ${res.status}`);
        setJobs(await res.json());
        setError(null);
      } catch (err) {
        if (err.name !== 'AbortError') setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    load();
    return () => controller.abort();
  }, []);

  if (loading) return <Spinner />;
  if (error) return <p className="err">{error}</p>;
  return <ul>{jobs.map(j => <li key={j.id}>{j.title}</li>)}</ul>;
}

How this works

fetch rejects only on network failure, so the explicit res.ok check is what turns a 404 or 500 into an error. The AbortController cleanup stops a slow response from setting state after the component has unmounted.

Key points to remember

  • The effect callback cannot be async — declare an inner async function and call it.
  • Always check res.ok; fetch treats HTTP error statuses as successful responses.
  • Abort in the cleanup to avoid race conditions when the parameters change quickly.

Common mistakes with Fetching Data with useEffect

  • Marking the effect callback async, so React receives a promise instead of a cleanup function.
  • Assuming fetch throws on a 500 response.
  • Forgetting to reset the error state on a successful retry.

React Fetching Data with useEffect— Interview Questions & FAQs

Why does my data fetch run twice?+

StrictMode in development mounts and remounts each component to verify cleanup. With an AbortController in place the duplicate is cancelled harmlessly, and production fetches once.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships