In modern web development, React API call is one of the most essential tasks. Whether you’re fetching user data, sending a form, or displaying live content, knowing how to develop a simple API call in React can greatly enhance your application functionality.
In this guide, we’ll break down how to call APIs using Axios in React and take it further with the power of React Query for effective data fetching and caching.
What is an API Call in React?
An Api call in React or an Api call in ReactJS is a way to communicate with external services like a backend server or third-party API like Weather, payment or user authentication services. It allows your React app to send and receive data asynchronously.
Some of the Common use Cases of React Api Calling:
- Axios: Axios is a promise-based HTTP client.
- React Query: Data fetching, caching and synchronization.
- React: JavaScript library for building user interfaces, particularly single-page web applications.
Call API Using Axios in React
Let’s walk through a simple example to call an API using Axios in React.
npm install axios
Import React, {useEffect,useState} from “react”
Import axios from “axios”
const userList=()=>{
const[user,setuser]=useState([ ]);
useEffect(()=>{
axios.get(“https://jsonplaceholder.typicode.com/users”).then((res)=>setUsers(res.data))
}).catch((error)=>console.error(“Api call error”,error))
},[ ])
return(
<div>
<h2>User List</h2>
{user.map((user)=>(
<div key={user.id}>{user.name}</div>
))}
</div>
)
export default UserListThat’s how you develop a simple API call in React using Axios.
Now the Power Up with React Query for Smarter Data Fetching while Axios handle the HTTP part, React Query makes data fetching powerful by handling caching, background updates and retries.
First things first, install the required npm packages
npm install @tanstack/react-query
Wrap Your App in QueryClientProvider, or you can wrapit in the root of the App.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
const App = () => (
<QueryClientProvider client={queryClient}>
<UserList />
</QueryClientProvider>
);
Use useQuery Hook for API Calling in React
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
const fetchUsers = async () => {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
return response.data;
};
const UserList = () => {
const { data: users, isLoading, error } = useQuery(['users'], fetchUsers);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error fetching users</p>;
return (
<div>
<h2>User List (With React Query)</h2>
{users.map((user) => (
<div key={user.id}>{user.name}</div>
))}
</div>
)};
Axios is a powerful and flexible HTTP client used to make API requests. However, on its own, it only handles the basic tasks:
- Manual request handling
- No built-in caching
- No automatic refetching or background updates
- Manual pagination implementation
- No stale-while-revalidate logic
Axios + React Query
Pairing Axios with React Query unlocks advanced features that make data fetching much more powerful and developer-friendly:
- Pairing Axios with React Query unlocks advanced features that make data fetching much more powerful and developer-friendly:
- Data Caching: React Query automatically caches API responses behind the scenes to minimise redundant requests and improve performance.
- Auto Refetching: Data can be automatically refreshed in the background, especially on window focus or network reconnect.
- Pagination Support: Easily manage paginated responses with built-in hooks and helper functions.
- Stale-While-Revalidate Logic: React Query serves stale data instantly while it fetches the latest version in the background, ensuring both speed and freshness.
Best Practices for Api Calls in React
- Always handle errors.
- Use loading indicators
- Avoid duplicate calls using caching ( React Query helps)
- Organise your Api logic in separate files.
- Use environment variables for API URLs.
Final Thoughts
Making an API call in React is a fundamental skill every frontend developer needs. While Axios or fetch handles the request itself, React Query adds robustness and performance to your data layer. By combining both, you can develop scalable, user-friendly apps with minimal boilerplate and maximum performance.