Skip to content

Axios with React

Axios is a popular HTTP client with interceptors, automatic JSON transforms, and request cancellation. It wraps XMLHttpRequest/fetch with a convenient API many React teams prefer over raw fetch.

Axios Instance Setup

Create an axios instance with baseURL, default headers, and timeout. Interceptors attach auth tokens to outgoing requests and normalize errors on responses.

Use axios functions as TanStack Query queryFn callbacks — axios plays well with query libraries.

import axios from 'axios';

const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

export const getUser = (id) => api.get(`/users/${id}`).then(r => r.data);

Central instance avoids repeating baseURL and auth logic.

Axios vs fetch

// axios throws on 4xx/5xx by default (configurable)
const { data } = await api.get('/users');

// fetch requires manual ok check
const res = await fetch('/users');
if (!res.ok) throw new Error(...);
const data = await res.json();
  • axios auto-parses JSON response bodies.
  • Interceptors for global auth and error handling.
  • Cancel requests with AbortController (v1+) or CancelToken (legacy).
  • fetch is built-in; axios adds ~13KB gzipped.

Axios API Reference

Common axios methods and config.

Method Usage
GET api.get('/path', { params: { q } })
POST api.post('/path', body)
PUT/PATCH api.patch('/path', partial)
DELETE api.delete('/path')
Instance axios.create({ baseURL })
Interceptor api.interceptors.response.use

Axios + TanStack Query

Pass axios-based fetchers directly to useQuery — caching and deduplication come from Query, HTTP from axios.

useQuery({
  queryKey: ['users', id],
  queryFn: () => api.get(`/users/${id}`).then(r => r.data),
});

Global Error Interceptor

Response interceptors can redirect to login on 401, show toast on 500, and transform error shapes consistently.

Common Mistakes

  • Creating new axios instance per request instead of shared client.
  • Not handling network errors separately from HTTP errors.
  • Storing tokens insecurely for interceptors to read.
  • Adding axios when fetch suffices for trivial needs.

Key Takeaways

  • Axios provides interceptors and ergonomic JSON APIs.
  • Create one configured instance per API backend.
  • Integrates cleanly with TanStack Query queryFn.
  • Weigh bundle size vs features against native fetch.

Pro Tip

Type axios responses with generics: api.get<User>(/users/${id}) in TypeScript projects.