Configuring Axios Instances for Reuse
Understand how to configure and reuse Axios instances to centralize API settings like base URL, headers, and timeouts. Learn to streamline data fetching in React by separating network logic from UI components, improving maintainability and scalability of your applications.
As projects grow, API calls start multiplying — fetching users, posts, comments, settings — each needing identical headers, timeouts, and error handling. Writing these options in every axios.get() call creates redundancy and inconsistency. React encourages composability and reuse, and Axios makes this easy through instances.
Understand Axios instance
An Axios instance lets us define all our defaults — like a base URL, common headers, or timeout — once, and reuse them everywhere. This keeps components focused on rendering logic while API details stay neatly abstracted away.
An Axios instance is a preconfigured copy of Axios. Instead of using the global axios, we create our own version with specific defaults.
import axios from "axios";const client = axios.create({baseURL: "/api",timeout: 2000,headers: { "X-App-Source": "Educative" },});
Every time we call client.get() or client.post(), Axios automatically uses these defaults — so we don’t have to repeat them.
This pattern keeps large React apps cleaner, and later makes it easy to attach interceptors ...