Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Fetching Data with useEffect

Recommended resources

Hello! Welcome to our next lesson.

In our previous session, we established a crucial foundation by learning how to use the useEffect cleanup function to prevent memory leaks and, most importantly, race conditions with asynchronous operations. We saw how tools like the AbortController ensure that our components behave predictably, even when effects are re-triggered rapidly.

Today, we'll put that knowledge into practice with one of the most common tasks in web development: fetching data from an external API. You'll learn how to use useEffect to retrieve data when a component loads and update its state to display that data. We'll start with the fundamental pattern and then see how it connects directly back to the cleanup logic we've already covered.

Your proficiency with async/await in JavaScript will be very helpful here, as we'll see how it makes data-fetching code inside React components clean and readable.

1. The Core Data Fetching Pattern

Most web applications need to display data that isn't hardcoded into the app itself—it comes from a server, a database, or another external source. In React, fetching this data is considered a side effect, because it's an interaction with the world outside of our component's rendering logic. This makes useEffect the perfect tool for the job.

The standard pattern involves three main parts:

  1. State (useState): A place to store the data once it arrives. We'll also type this state with TypeScript.
  2. Effect (useEffect): The hook that will trigger the data fetching process.
  3. Fetch API: The browser mechanism for making the network request.

Let's see this in action. This first video provides a fantastic, practical demonstration of this entire pattern.

Fetching Data in React - Complete Tutorial

This segment from a tutorial by Cosden Solutions clearly demonstrates the fundamental pattern of fetching data. It covers everything from setting up the useEffect hook to handling the asynchronous request and updating state with TypeScript.

Please watch from 01:44 to 06:28. Pay close attention to these key steps: Using useEffect with an empty dependency array ([]) to run the fetch only on component mount. Defining an async function inside the effect to use async/await. Using the fetch API and await response.json() to get the data. Applying a TypeScript interface to type the fetched data for type safety. Calling the state setter function (e.g., setPosts) to trigger a re-render with the new data.

Deconstructing the Code

As you saw in the video, the code structure is logical and builds upon concepts we've already learned. Here is a summary of the pattern, including the TypeScript definitions:

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

// 1. Define the shape of our data with a TypeScript interface.
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

function PostsList() {
  // 2. Create state to hold the array of posts.
  // We initialize it as an empty array of type Post[].
  const [posts, setPosts] = useState<Post[]>([]);

  // 3. Use useEffect to perform the side effect (data fetching).
  useEffect(() => {
    // We define an async function inside the effect so we can use await.
    const fetchPosts = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
        // Type assertion tells TypeScript to trust us that the JSON will match the Post[] interface.
        const data: Post[] = await response.json(); 
        setPosts(data);
      } catch (error) {
        console.error("Failed to fetch posts:", error);
      }
    };

    fetchPosts(); // Call the function.

  // 4. An empty dependency array means this effect runs only once, after the initial render.
  }, []); 

  // 5. Render the data.
  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default PostsList;

This pattern is the bedrock of data fetching in client-side React. The useEffect hook ensures the fetch doesn't block the initial render, and useState ensures the component re-renders to display the data once it's available.

For a text-based alternative that reinforces this same pattern, the following article is a great supplement.

Modern API data-fetching methods in React

This article from LogRocket provides a clear, written explanation of the same pattern. It's a good way to review the concepts from the video in a different format.

Read the section titled 'API calls with fetch() in a useEffect Hook'. Notice the similar structure: useState for data, useEffect with an empty dependency array, and an async function inside to handle the fetch call.

Test your understanding!

In the useEffect hook, we define a separate async function (fetchPosts) and then immediately call it. Why don't we just make the function passed to useEffect itself async?

For example, why is this not allowed?

// This will cause an error. Why?
useEffect(async () => {
  const response = await fetch('...');
  const data = await response.json();
  setPosts(data);
}, []);
Show answer

An async function implicitly returns a Promise. However, the useEffect hook has a specific requirement for its return value: it must either return nothing (undefined) or a cleanup function.

If you make the effect callback async, it will return a Promise, which is not a function. React will see this and throw an error because it's expecting a potential cleanup function, not a promise. The correct pattern is to define a nested async function inside the effect and call it, which keeps the effect's direct return value as undefined.


2. Handling Re-fetches and Connecting to Our Previous Lesson

The example above is perfect for when you need to fetch data only once. But what if the data you need depends on a prop or some other state? For example, fetching a specific user's data based on a userId prop, or fetching a specific page of results in a paginated list.

This is where our last lesson on cleanup functions becomes critical. If we add a variable to the useEffect dependency array, the effect will re-run every time that variable changes, triggering a new fetch. Without proper cleanup, this can lead to the exact race conditions we discussed.

The following video segment demonstrates this scenario perfectly. It extends the basic fetching logic to handle pagination, where clicking a "next page" button triggers a re-fetch. It then shows how to implement the AbortController pattern we learned about to prevent race conditions.

Fetching Data in React - Complete Tutorial

Now, let's see how to handle re-fetches safely. This part of the 'Fetching Data in React' video shows how to add a dependency to the effect and why that necessitates using an AbortController to cancel previous, now-outdated requests.

Watch from 15:35 to 27:08. This is a more advanced but very practical section. Focus on: How a page state variable is added to the useEffect dependency array. The explanation of the race condition: a slow response from page 1 arriving after a fast response from page 2. How useRef is used to store the AbortController instance across renders. The logic to abort() the previous request before a new one is initiated. How the catch block is updated to specifically ignore the AbortError.

This powerfully connects the theory of cleanup functions to the practical reality of building dynamic user interfaces. The AbortController isn't just an abstract concept; it's the standard tool for ensuring data consistency when fetching data that depends on changing inputs.

Here is the key takeaway pattern for re-fetching data:

// Assume `page` is a state variable: const [page, setPage] = useState(1);
const abortControllerRef = useRef<AbortController | null>(null);

useEffect(() => {
  // Abort the previous request before starting a new one.
  if (abortControllerRef.current) {
    abortControllerRef.current.abort();
  }

  // Create a new AbortController for the new request.
  abortControllerRef.current = new AbortController();
  const signal = abortControllerRef.current.signal;

  const fetchData = async () => {
    try {
      const response = await fetch(`https://api.example.com/data?page=${page}`, { signal });
      const data = await response.json();
      setData(data);
    } catch (error: any) {
      if (error.name === 'AbortError') {
        console.log('Fetch aborted'); // This is expected, not a "real" error.
      } else {
        // Handle actual network or server errors.
        setError(error);
      }
    }
  };

  fetchData();
  
  // No explicit cleanup function needed here because the abort logic runs at the start of the effect.
  // An alternative is to return () => abortControllerRef.current?.abort();

}, [page]); // Re-run the effect whenever 'page' changes.

Conclusion

In this lesson, we've covered the complete lifecycle of fetching data in a React component. We've seen how to initiate requests, update state, and most importantly, how to handle these asynchronous operations safely.

Key Takeaways:

  • Data fetching is a side effect, making useEffect the appropriate hook to use.
  • The basic pattern combines useState to store data with a useEffect hook that runs on mount ([] dependency array) to perform the fetch.
  • For effects that re-run based on changing dependencies (like a search query or page number), you must implement a cleanup strategy like AbortController to prevent race conditions. This directly applies what we learned in the previous lesson.

The pattern we've used is robust, but the user experience can still be improved. Right now, the user might see a blank screen while data is loading, or nothing might happen if an error occurs. In our next lesson, we will focus on managing loading and error states to provide clear feedback to the user throughout the data fetching process.