REACT Tutorial



DATA FETCHING AND APIs


Data Fetching and APIs in React

Fetching data from APIs is a fundamental part of building React applications. Whether you want to display user info, fetch posts, or get weather data, React offers simple ways to interact with external APIs and handle asynchronous data.

Why Data Fetching Matters

Most modern apps are dynamic β€” they rely on external data. React components often need to fetch data asynchronously, update the UI once data arrives, and handle loading or error states gracefully.

Using fetch() in React

The JavaScript fetch() API is commonly used to request data. Here’s how you fetch data inside a React functional component using the useEffect hook:

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

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

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        if (!response.ok) throw new Error('Network error');
        return response.json();
      })
      .then(data => {
        setUsers(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <p style={{color: '#1e90ff', fontWeight: '600'}}>Loading users...</p>;
  if (error) return <p style={{color: 'red', fontWeight: '600'}}>Error: {error}</p>;

  return (
    <ul style={{ listStyle: 'none', paddingLeft: 0 }}>
      {users.map(user => (
        <li key={user.id} style={{ marginBottom: '10px', padding: '8px', background: '#e1f5fe', borderRadius: '6px' }}>
          <strong>{user.name}</strong> β€” {user.email}
        </li>
      ))}
    </ul>
  );
}

Understanding the Code

  • useState hooks: Manage users data, loading state, and error message.
  • useEffect hook: Runs the fetch once when the component mounts (empty dependency array []).
  • fetch(): Requests user data from a fake API endpoint.
  • Loading & Error handling: Displays informative UI messages while data is loading or if errors happen.
  • Rendering: Maps the fetched users to a styled list dynamically.

Using Async/Await for Cleaner Code

Async/await syntax helps write asynchronous code more readably. Here’s the same fetch example rewritten with async/await:

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

function UsersList() {
  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 style={{color: '#1e90ff', fontWeight: '600'}}>Loading users...</p>;
  if (error) return <p style={{color: 'red', fontWeight: '600'}}>Error: {error}</p>;

  return (
    <ul style={{ listStyle: 'none', paddingLeft: 0 }}>
      {users.map(user => (
        <li key={user.id} style={{ marginBottom: '10px', padding: '8px', background: '#e1f5fe', borderRadius: '6px' }}>
          <strong>{user.name}</strong> β€” {user.email}
        </li>
      ))}
    </ul>
  );
}

Best Practices for Data Fetching

  • Always handle loading and error states to improve user experience.
  • Cancel fetch requests if the component unmounts to avoid memory leaks (use AbortController).
  • Use tools like React Query or Redux Toolkit Query for advanced data fetching & caching.
  • Keep your components pure and side-effect-free by handling data fetching in hooks or container components.

Using Axios for Data Fetching

Axios is a popular third-party library that simplifies HTTP requests and supports features like interceptors and automatic JSON parsing.

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

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

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/users')
      .then(response => {
        setUsers(response.data);
        setLoading(false);
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);
      });
  }, []);

  if (loading) return 

Loading users...

; if (error) return

Error: {error}

; return (
    {users.map(user => (
  • {user.name} β€” {user.email}
  • ))}
); }
Practice fetching data with both fetch() and axios, handle errors, loading states, and render your UI dynamically β€” this skill is key for real-world React apps!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review