React API Calls (Fetch & Axios)

📘 React.js 👁 39 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

API calls are used in React to retrieve or send data to a server. The most common ways to make HTTP requests are using the Fetch API (built-in) and Axios (third-party library).


Where to Make API Calls in React

API calls are usually made inside the useEffect hook to avoid repeated requests.

useEffect(() => { // API call here }, []);

Using Fetch API

Basic GET Request

import { useEffect, useState } from "react"; function Users() { const [users, setUsers] = useState([]); useEffect(() => { fetch("https://api.example.com/users") .then(response => response.json()) .then(data => setUsers(data)) .catch(error => console.error(error)); }, []); return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

POST Request with Fetch

fetch("https://api.example.com/users", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Alice" }) });

Using Axios

Installation

npm install axios

Basic GET Request

import axios from "axios"; useEffect(() => { axios.get("https://api.example.com/users") .then(res => setUsers(res.data)) .catch(err => console.error(err)); }, []);

POST Request with Axios

axios.post("https://api.example.com/users", { name: "Alice" });

Fetch vs Axios

FetchAxios
Built-inExternal library
Manual JSON parsingAuto JSON parsing
Less featuresInterceptors, defaults
More boilerplateCleaner syntax

Handling Loading and Errors

const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(url) .then(res => res.json()) .then(data => { setData(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []);

Using Async/Await

useEffect(() => { async function fetchData() { try { const res = await axios.get(url); setData(res.data); } catch (err) { console.error(err); } } fetchData(); }, []);

Cleanup & Abort (Advanced)

useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); }, []);

Best Practices

  • Use useEffect for API calls

  • Handle loading and error states

  • Clean up requests on unmount

  • Separate API logic when possible


Key Points

  • API calls fetch data from servers

  • Fetch and Axios are common tools

  • Axios simplifies request handling

  • Always handle loading & errors


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes