When to Use Context vs a State Management Library :👈 👉:How to Handle Loading, Error, Empty, and Success States

How to Organize API Calls in a React Application

1. Introduction

In a React application, API calls are used to communicate with backend services and retrieve or send data.

For example, an e-commerce application may need APIs to:

  • Fetch product details.
  • Retrieve customer information.
  • Create orders.
  • Update shopping cart items.
  • Delete products.
  • Authenticate users.

A common beginner approach is to write fetch() or axios directly inside React components.

This works for small applications, but as the application grows, API-related code becomes difficult to maintain.

Recommended approach: Separate API communication from UI components by using dedicated API service files, reusable HTTP configuration and custom Hooks or data-fetching libraries where appropriate.

2. Why Should You Organize API Calls?

Keeping API calls organized provides several benefits:

  1. Reusability: The same API function can be used by multiple components.
  2. Maintainability: API changes can be handled in one place.
  3. Separation of concerns: Components focus on UI, while service files handle HTTP communication.
  4. Consistency: Common headers, authentication and error handling can be centralized.
  5. Testability: API functions can be tested independently.
  6. Scalability: New API endpoints can be added without making components unnecessarily complicated.

3. Recommended Folder Structure

For a medium-sized React application, you can organize API-related files as follows:

src/
│
├── api/
│   ├── httpClient.js
│   ├── authApi.js
│   ├── userApi.js
│   ├── productApi.js
│   └── orderApi.js
│
├── components/
│   ├── UserCard.jsx
│   └── ProductCard.jsx
│
├── features/
│   ├── users/
│   │   ├── UserList.jsx
│   │   └── useUsers.js
│   │
│   └── products/
│       ├── ProductList.jsx
│       └── useProducts.js
│
├── hooks/
│   └── useDebounce.js
│
├── pages/
│   ├── UsersPage.jsx
│   └── ProductsPage.jsx
│
├── App.jsx
└── main.jsx

Responsibilities:

Folder/File Responsibility
api/ API communication and endpoint functions
httpClient.js Common HTTP configuration and request handling
userApi.js User-related API functions
productApi.js Product-related API functions
features/ Feature-specific components and Hooks
hooks/ Reusable custom Hooks
components/ Reusable UI components
pages/ Application pages

4. Step 1: Create a Common HTTP Client

Instead of configuring the base URL and common headers in every API function, create a reusable HTTP client.

You can use the native Fetch API or Axios. Both are valid options.

Option A: Using Native Fetch

Create api/httpClient.js:

const BASE_URL = import.meta.env.VITE_API_BASE_URL;
export async function apiRequest(
  endpoint,
  {
    method = "GET",
    body,
    headers = {},
    signal
  } = {}
) {
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers
    },
    body: body === undefined ? undefined : JSON.stringify(body),
    signal
  });
  if (!response.ok) {
    const errorBody = await response.json().catch(() => null);
    throw new Error(
      errorBody?.message || `HTTP Error: ${response.status}`
    );
  }
  if (response.status === 204) {
    return null;
  }
  return response.json();
}

Explanation:

  • BASE_URL stores the common backend URL.
  • method specifies GET, POST, PUT, PATCH or DELETE.
  • headers allows additional request headers.
  • body contains request data for operations such as POST and PUT.
  • signal supports request cancellation using AbortController.
  • response.ok checks whether the HTTP status indicates success.
  • 204 means the server returned no content.

Important: Fetch does not automatically throw an error for HTTP 400 or 500 responses. Therefore, checking response.ok is necessary.

This example assumes successful responses contain JSON, except for HTTP 204. If your backend returns text, files or other response formats, handle those separately.

Option B: Using Axios

Install Axios:

npm install axios

Create api/httpClient.js:

import axios from "axios";
const httpClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json"
  }
});
export default httpClient;

Axios provides:

  • Automatic JSON request and response handling in common cases.
  • Request and response interceptors.
  • Request timeout configuration.
  • Convenient error objects.
  • Request cancellation support.

You generally do not need to create both clients. Choose Fetch or Axios based on your project requirements.

5. Step 2: Create API Service Files

Keep API functions organized by feature or business domain.

Example: User API

Create api/userApi.js using the Fetch-based HTTP client:

import { apiRequest } from "./httpClient";
export function getUsers(signal) {
  return apiRequest("/users", { signal });
}
export function getUserById(id, signal) {
  return apiRequest(`/users/${id}`, { signal });
}
export function createUser(user) {
  return apiRequest("/users", {
    method: "POST",
    body: user
  });
}
export function updateUser(id, user) {
  return apiRequest(`/users/${id}`, {
    method: "PUT",
    body: user
  });
}
export function deleteUser(id) {
  return apiRequest(`/users/${id}`, {
    method: "DELETE"
  });
}

Example: Product API

Create api/productApi.js:

import { apiRequest } from "./httpClient";
export function getProducts(signal) {
  return apiRequest("/products", { signal });
}
export function getProductById(id, signal) {
  return apiRequest(`/products/${id}`, { signal });
}
export function createProduct(product) {
  return apiRequest("/products", {
    method: "POST",
    body: product
  });
}
export function updateProduct(id, product) {
  return apiRequest(`/products/${id}`, {
    method: "PUT",
    body: product
  });
}
export function deleteProduct(id) {
  return apiRequest(`/products/${id}`, {
    method: "DELETE"
  });
}

Now API communication is separated from the React components.

6. Step 3: Call API Services from React Components

For a simple application, you can call API service functions inside useEffect and manage loading, error and data states using useState.

Create features/users/UserList.jsx:

import { useEffect, useState } from "react";
import { getUsers } from "../../api/userApi";
function UserList() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  useEffect(() => {
    const controller = new AbortController();
    async function loadUsers() {
      try {
        setLoading(true);
        setError("");
        const data = await getUsers(controller.signal);
        setUsers(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          setError(error.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }
    loadUsers();
    return () => {
      controller.abort();
    };
  }, []);
  if (loading) {
    return <p>Loading users...</p>;
  }
  if (error) {
    return <p>Error: {error}</p>;
  }
  return (
    <div>
      <h2>User List</h2>
      {users.map(user => (
        <div key={user.id}>
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      ))}
    </div>
  );
}
export default UserList;

What happens here?

  1. The component renders.
  2. useEffect calls the user API service.
  3. The API service communicates with the backend.
  4. The response is stored in React state.
  5. The component renders the user information.
  6. If the component unmounts, the request is cancelled.

7. Step 4: Extract API Logic into a Custom Hook

As applications grow, even components that use API service functions can become complicated.

You can extract reusable data-fetching logic into a custom Hook.

Create features/users/useUsers.js:

import { useEffect, useState } from "react";
import { getUsers } from "../../api/userApi";
export function useUsers() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  useEffect(() => {
    const controller = new AbortController();
    async function loadUsers() {
      try {
        setLoading(true);
        setError("");
        const data = await getUsers(controller.signal);
        setUsers(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          setError(error.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }
    loadUsers();
    return () => controller.abort();
  }, []);
  return {
    users,
    loading,
    error
  };
}

Now the component becomes much simpler.

import { useUsers } from "./useUsers";
function UserList() {
  const { users, loading, error } = useUsers();
  if (loading) {
    return <p>Loading users...</p>;
  }
  if (error) {
    return <p>Error: {error}</p>;
  }
  return (
    <div>
      <h2>User List</h2>
      {users.map(user => (
        <div key={user.id}>
          <h3>{user.name}</h3>
          <p>{user.email}</p>
        </div>
      ))}
    </div>
  );
}

Benefits:

  • API-related state management is separated from UI.
  • Multiple components can reuse the Hook.
  • Components become easier to read.
  • Loading and error handling can be standardized.

8. How to Organize POST, PUT, PATCH and DELETE Requests

GET requests retrieve data, while POST, PUT, PATCH and DELETE requests generally perform operations that modify server data.

POST - Create a User

async function handleCreateUser(user) {
  try {
    const result = await createUser(user);
    console.log("User created:", result);
  } catch (error) {
    console.error(error.message);
  }
}

PUT - Replace or Update a User Resource

async function handleUpdateUser(id, user) {
  try {
    await updateUser(id, user);
    console.log("User updated successfully");
  } catch (error) {
    console.error(error.message);
  }
}

PATCH - Partially Update a User

Add a PATCH function to userApi.js:

export function patchUser(id, changes) {
  return apiRequest(`/users/${id}`, {
    method: "PATCH",
    body: changes
  });
}

DELETE - Remove a User

async function handleDeleteUser(id) {
  try {
    await deleteUser(id);
    console.log("User deleted successfully");
  } catch (error) {
    console.error(error.message);
  }
}

Keep these functions inside API service files rather than repeating HTTP request code in multiple components.

9. How to Handle Authentication Tokens?

Many applications require authentication tokens when communicating with protected APIs.

With Axios, you can configure a request interceptor to attach an access token.

import axios from "axios";
const httpClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL
});
httpClient.interceptors.request.use(config => {
  const token = getAccessToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});
export default httpClient;

getAccessToken() represents your application's token-access logic; it must be implemented using an appropriate authentication strategy.

Security considerations:

  • Do not hardcode access tokens in source code.
  • Do not put secrets or private API keys in frontend environment variables. Frontend environment variables are included in the client application and can be inspected.
  • For browser applications, consider secure, HttpOnly, SameSite cookies where appropriate.
  • Protect backend endpoints with server-side authentication and authorization.
  • Do not assume hiding a UI button provides security.

10. How to Handle Global API Errors?

Instead of implementing different error-handling rules in every component, establish a consistent error-handling strategy.

For example, with Axios:

httpClient.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      console.log("Authentication required");
    }
    if (error.response?.status === 403) {
      console.log("Access denied");
    }
    if (error.response?.status >= 500) {
      console.log("Server error");
    }
    return Promise.reject(error);
  }
);

Common HTTP status codes:

Status Code Meaning Typical Handling
200 OK Process successful response
201 Created Handle newly created resource
204 No Content Do not expect a response body
400 Bad Request Display validation or request errors
401 Unauthorized Handle authentication requirements
403 Forbidden Display access-denied information
404 Not Found Handle missing resources
500 Internal Server Error Display a suitable server error message

Interceptors can centralize common handling, but feature-specific errors should still be handled where the application can provide useful feedback to the user.

11. When Should You Use TanStack Query or RTK Query?

For larger applications, manually managing API loading, caching, errors, refetching and synchronization in every custom Hook can become repetitive.

Libraries such as TanStack Query and RTK Query provide dedicated solutions for managing server state.

Example: TanStack Query

Install the library:

npm install @tanstack/react-query

Configure the Query Client in main.jsx:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
function Main() {
  return (
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  );
}
export default Main;

Create a reusable API function:

async function fetchUsers({ signal }) {
  const response = await fetch("/api/users", { signal });
  if (!response.ok) {
    throw new Error("Failed to fetch users");
  }
  return response.json();
}

Use it inside a component:

import { useQuery } from "@tanstack/react-query";
function UserList() {
  const {
    data: users,
    isLoading,
    error
  } = useQuery({
    queryKey: ["users"],
    queryFn: fetchUsers
  });
  if (isLoading) {
    return <p>Loading users...</p>;
  }
  if (error) {
    return <p>{error.message}</p>;
  }
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

TanStack Query provides features such as:

  • Automatic caching based on query keys.
  • Background refetching.
  • Loading and error state management.
  • Request deduplication in appropriate situations.
  • Cache invalidation.
  • Mutation management.

It is particularly useful when multiple components need the same server data.

12. Fetch API vs Axios vs TanStack Query

Feature Fetch Axios TanStack Query
Type Browser API HTTP client library Server-state library
Installation Built into modern browsers Required Required
HTTP requests Yes Yes Uses a query function such as Fetch or Axios
Automatic HTTP error rejection No Usually for non-2xx responses Depends on query function rejecting errors
Interceptors No built-in interceptors Yes Not its primary responsibility
Automatic caching No No Yes
Background refetching Manual implementation Manual implementation Supported
Best use Simple HTTP requests Reusable HTTP client configuration Server-state management

Important: Fetch and Axios are HTTP communication tools. TanStack Query manages server-state behavior. They solve related but different problems and can be used together.

13. Common Mistakes to Avoid

  1. Writing API calls directly in every component: Move reusable HTTP communication into API service files.
  2. Duplicating base URLs: Use a common HTTP client configuration.
  3. Ignoring loading states: Always provide suitable loading feedback.
  4. Ignoring errors: Handle network errors and unsuccessful HTTP responses.
  5. Not cancelling outdated requests: Use AbortController where appropriate.
  6. Fetching data during rendering: Do not initiate API requests directly in the component render body.
  7. Using useEffect for every server-state problem: Consider TanStack Query or RTK Query when caching and synchronization become important.
  8. Putting all API functions in one huge file: Organize API functions by feature or domain.
  9. Duplicating server data in multiple places: Establish a clear source of truth.
  10. Trusting API response types without validation: Validate untrusted external data at runtime when necessary.

14. Recommended Architecture

A scalable React application can organize API communication as follows:

React Application
│
├── Pages
│   ├── UsersPage
│   └── ProductsPage
│
├── Features
│   ├── Users
│   │   ├── UserList
│   │   └── useUsers
│   │
│   └── Products
│       ├── ProductList
│       └── useProducts
│
├── API
│   ├── httpClient
│   ├── userApi
│   ├── productApi
│   └── orderApi
│
├── Components
│   ├── Loading
│   ├── ErrorMessage
│   └── Pagination
│
└── App

Request flow:

⚛️ React Component 🪝 Custom / Query Hook ⚙️ API Service Function 🌐 Common HTTP Client 🗄️ Backend API 📦 HTTP Response 💾 State / Query Cache 🔄 UI Update

15. Best Practices

  1. Create a common HTTP client for shared request configuration.
  2. Keep API functions separate from UI components.
  3. Organize API files by business domain or feature.
  4. Use custom Hooks when reusable stateful API logic is needed.
  5. Use TanStack Query or RTK Query for more complex server-state requirements.
  6. Handle loading, error and empty states consistently.
  7. Use AbortController to cancel requests when appropriate.
  8. Keep authentication and authorization responsibilities secure on the backend.
  9. Use environment variables for configurable API base URLs, but never expose secrets in frontend variables.
  10. Validate API data at runtime when data comes from untrusted sources.
  11. Test API service functions independently.
  12. Avoid introducing unnecessary abstraction for a small application.

16. Common Interview Questions

Q1. Why should API calls be separated from React components?

To improve reusability, maintainability, testability and separation of concerns. Components can focus on UI while API service files handle HTTP communication.

Q2. What is an API service file?

An API service file contains reusable functions responsible for communicating with backend endpoints, such as fetching users, creating orders and updating products.

Q3. What is the difference between an API service and a custom Hook?

An API service performs HTTP communication. A custom Hook manages reusable React-related logic such as loading, error and data state.

Q4. Why should we use a common HTTP client?

It centralizes base URL configuration, common headers, authentication handling, timeouts and other shared request behavior.

Q5. What is the difference between Fetch and Axios?

Fetch is a built-in browser API, while Axios is an external HTTP client library with features such as interceptors and convenient request configuration.

Q6. Why should we use TanStack Query?

It simplifies server-state management by providing caching, refetching, loading and error states, request deduplication and cache invalidation.

Q7. What is AbortController?

AbortController is a browser API used to cancel supported asynchronous operations, including Fetch requests.

Q8. Should we store API responses in Context?

It is possible, but for applications with caching, refetching and synchronization requirements, a dedicated server-state library is often more suitable.

Q9. What is the difference between client state and server state?

Client state is managed by the frontend, such as modal visibility and selected tabs. Server state originates from backend APIs and requires additional handling for caching and synchronization.

Q10. Where should authentication tokens be attached to API requests?

A common HTTP client or authentication-aware request layer can attach credentials consistently. The token storage and transmission approach must be selected carefully based on the application's security requirements.

17. Final Takeaway

A well-organized React application should keep API communication separate from UI presentation.

  • API Service: Handles HTTP requests.
  • HTTP Client: Handles common request configuration.
  • Custom Hook: Reuses React stateful API logic.
  • TanStack Query / RTK Query: Manages server-state caching and synchronization.
  • React Component: Displays data and handles user interactions.

Recommended approach: Start with a common HTTP client and feature-based API service files. Add custom Hooks or a server-state library when the application requires them. Keep the architecture simple and introduce abstractions only when they provide a real benefit.

🔙
When to Use Context vs a State Management Library :👈 👉:How to Handle Loading, Error, Empty, and Success States

Comments and Discussion