🌐 React API Integration & Data Fetching
Estimated reading: 4 minutes 41 views

🌐 React API Calls using Fetch & Axios – Complete Integration Guide (2025)


🧲 Introduction – Why API Calls Matter in React

React.js apps often need to interact with external servicesβ€”REST APIs, GraphQL endpoints, or backend servers. Whether you’re loading user data, submitting forms, or integrating with third-party services, making API calls is essential.

React supports multiple ways to fetch data, but the most common are:

  • fetch – native browser API
  • Axios – a popular, feature-rich HTTP client

🎯 In this guide, you’ll learn:

  • How to perform GET/POST requests using fetch and axios
  • How to handle loading, success, and error states
  • When to use each approach
  • Best practices for reusable API logic in React

βš™οΈ 1. Using the Native fetch API

fetch() is built into modern browsers and provides a promise-based interface to make HTTP requests.

βœ… Basic GET Request:

useEffect(() => {
  fetch('https://jsonplaceholder.typicode.com/posts')
    .then((res) => {
      if (!res.ok) throw new Error('Failed to fetch');
      return res.json();
    })
    .then((data) => setPosts(data))
    .catch((err) => setError(err));
}, []);

βœ… POST Request:

fetch('/api/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ title: 'React Rocks!' }),
});

πŸ§ͺ 2. Making API Calls with Axios

Axios simplifies HTTP calls by handling JSON parsing, request cancellation, and interceptors.

βœ… Install Axios:

npm install axios

βœ… Axios GET Request:

import axios from 'axios';

useEffect(() => {
  axios.get('https://jsonplaceholder.typicode.com/posts')
    .then((res) => setPosts(res.data))
    .catch((err) => setError(err));
}, []);

βœ… Axios POST Request:

axios.post('/api/posts', {
  title: 'Learning Axios with React',
  content: 'Axios makes HTTP easier',
});

πŸ†š 3. Fetch vs Axios – Feature Comparison

Featurefetchaxios
Built-inβœ… Yes❌ No (needs install)
JSON parsing❌ Manual .json()βœ… Automatic
Interceptors❌ Not supportedβœ… Yes
Request cancellationβœ… With AbortControllerβœ… With cancel token
Default headers❌ Noneβœ… application/json
Error handling❌ Manualβœ… Better structured

πŸ“¦ 4. Reusable API Call Functions

βœ… With fetch:

export async function fetchData(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error('Error fetching data');
  return await res.json();
}

βœ… With Axios:

import axios from 'axios';

export const apiClient = axios.create({
  baseURL: '/api',
  headers: { 'Content-Type': 'application/json' },
});

πŸ“˜ Use Axios interceptors to add tokens or log errors


πŸ” 5. useEffect + API Calls Pattern

useEffect(() => {
  let isMounted = true;
  fetchData('/api/data')
    .then(data => isMounted && setData(data))
    .catch(err => console.error(err));

  return () => {
    isMounted = false;
  };
}, []);

βœ… Prevents state update on unmounted component
βœ… Consider AbortController for fetch cleanup


🧠 6. API Call Use Cases in React

Use CaseMethodTool Suggestion
Get user dataGETfetch, axios
Submit formPOSTaxios
Update profilePUT/PATCHaxios, fetch
Delete itemDELETEaxios
Auth with tokenAnyaxios + interceptors

πŸ“˜ Best Practices

βœ… Use try/catch with async/await for readability
βœ… Manage loading and error states
βœ… Cancel long-running requests on unmount
βœ… Extract API logic into separate utility files
βœ… Handle HTTP error codes gracefully


πŸ“Œ Summary – Recap & Next Steps

Both fetch and Axios allow you to make powerful API calls in React. While fetch is native and lightweight, Axios offers a more ergonomic and feature-rich developer experienceβ€”especially in larger applications.

πŸ” Key Takeaways:

  • Use fetch() for native, simple API calls
  • Use Axios for larger apps with interceptors and error handling
  • Manage loading and errors using useState and useEffect
  • Cancel requests and avoid memory leaks
  • Abstract logic for reusability and scalability

βš™οΈ Real-World Relevance:
Used in production apps for dashboards, login flows, file uploads, and real-time data sync in apps like Airbnb, GitHub, and Slack.


❓ FAQ Section

❓ Should I use fetch or axios in React?
βœ… Use fetch for simple use cases and Axios for advanced needs like interceptors, auto JSON parsing, and cancellation.


❓ How do I handle API errors?
βœ… Use try/catch or .catch() to handle failures and show fallback UI or messages.


❓ Can I cancel an API request in React?
βœ… Yes. Use AbortController with fetch or CancelToken with Axios.


❓ Is useEffect required for API calls?
βœ… For component-based data loading, yes. It ensures the fetch runs after render and not during the render phase.


❓ How do I show a loading spinner during API calls?
βœ… Use a loading state with conditional rendering:

{loading ? <Spinner /> : <Data />}

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🌐 React API Calls using Fetch & Axios

Or Copy Link

CONTENTS
Scroll to Top