0
0
ReactHow-ToBeginner · 4 min read

How to Fetch Data in React: Simple Guide with Examples

In React, you fetch data by using the fetch API inside the useEffect hook to load data when the component mounts. Store the fetched data in state using useState to update the UI when data arrives.
📐

Syntax

To fetch data in React, use the useEffect hook to run the fetch call after the component renders. Use useState to save the data and trigger UI updates.

  • useEffect(() => { ... }, []): Runs once after first render.
  • fetch(url): Calls the API to get data.
  • setState(data): Saves data to state.
javascript
import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(json => setData(json));
  }, []);

  return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Output
Loading... (initially), then JSON data displayed as string
💻

Example

This example fetches a list of users from a public API and displays their names. It shows how to handle loading state and errors.

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

function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchUsers() {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }

    fetchUsers();
  }, []);

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UserList;
Output
<ul><li>Leanne Graham</li><li>Ervin Howell</li><li>Clementine Bauch</li><li>Patricia Lebsack</li><li>Chelsey Dietrich</li><li>Mrs. Dennis Schulist</li><li>Kurtis Weissnat</li><li>Nicholas Runolfsdottir V</li><li>Glenna Reichert</li><li>Clementina DuBuque</li></ul>
⚠️

Common Pitfalls

Common mistakes when fetching data in React include:

  • Not using useEffect properly, causing infinite loops by missing dependency arrays.
  • Not handling loading or error states, which confuses users.
  • Not checking if the fetch response is OK before parsing JSON.
  • Updating state after the component unmounts, causing memory leaks.

Always use useEffect with an empty dependency array to fetch once on mount, and handle errors and loading states gracefully.

javascript
/* Wrong: Missing dependency array causes infinite fetch loop */
useEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => setData(data));
});

/* Right: Add empty dependency array to run once */
useEffect(() => {
  fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => setData(data));
}, []);
📊

Quick Reference

  • Use useEffect(() => { ... }, []) to fetch data once on mount.
  • Use fetch or async/await to get data from APIs.
  • Store data in state with useState to trigger UI updates.
  • Handle loading and error states for better user experience.
  • Clean up or cancel fetch if component unmounts (advanced).

Key Takeaways

Always fetch data inside useEffect with an empty dependency array to avoid repeated calls.
Use useState to store fetched data and update the UI automatically.
Handle loading and error states to improve user experience.
Check fetch response status before parsing JSON to catch errors.
Avoid updating state after component unmount to prevent memory leaks.