React
/Intermediate
Axios
Definition
Axios is a popular third-party HTTP client library for the browser and Node.js. It acts as a wrapper around `XMLHttpRequest` (or standard HTTP in Node) to simplify requests.
Explain Like I'm New
If `fetch` is a standard manual transmission car, `axios` is an automatic luxury car. It does exactly the same job (gets you from point A to point B), but Axios automatically shifts gears for you—like automatically parsing JSON, automatically throwing errors on 404s, and letting you set default headers easily.
Real World Example
An enterprise app sets up an `axios.create()` instance with a `baseURL` of `api.company.com` and an interceptor that automatically attaches a JWT Auth token to every single request made by the app.
Common Use Cases
- •Complex enterprise applications requiring request interceptors
- •Apps making hundreds of API calls where reducing boilerplate (like `.json()`) is helpful
- •Upload progress tracking
Interactive Example
/* // Conceptual Example - Requires npm install axios import React, { useState, useEffect } from "react"; import axios from "axios"; // 1. Create a custom instance with defaults const api = axios.create({ baseURL: "https://jsonplaceholder.typicode.com", timeout: 5000 }); // 2. Add an Interceptor (runs before every request) api.interceptors.request.use(config => { console.log("Automatically adding auth headers!"); config.headers.Authorization = `Bearer fake-token-123`; return config; }); export default function AxiosDemo() { const [user, setUser] = useState(null); useEffect(() => { // 3. Make the request. Notice how much cleaner this is than fetch! api.get("/users/1") .then(response => { // Axios automatically parses the JSON and puts it in `response.data` setUser(response.data); }) .catch(error => { // Axios automatically throws errors for 404 or 500 status codes! console.error("Request failed:", error.message); }); }, []); return <div>{user ? user.name : "Loading..."}</div>; } */ console.log("Axios is an industry standard library, but fetch is catching up.");
Interview Questions
basic
- Why would someone use Axios instead of native Fetch?
- Do you need to call `.json()` when using Axios?
intermediate
- What is an Axios Interceptor?
- How does Axios handle 404 and 500 status codes compared to Fetch?
advanced
- How do you cancel an Axios request?
- How can you handle global authentication token refresh using Axios interceptors?
trick
- Is Axios faster than Fetch?