REST APIs: Fetch, Axios and React Query
Harry
· 28 Sep 2026
· 1 views
Log in to track your progress and mark lessons complete.
Sponsored
Plain fetch (Know It Cold)
const res = await fetch("/api/books", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, price }),
})
if (!res.ok) throw new Error("HTTP " + res.status)
const created = await res.json()Axios for Ergonomics
npm i axios
const api = axios.create({ baseURL: "/api", timeout: 10000 })
api.interceptors.request.use(cfg => {
cfg.headers.Authorization = `Bearer ${localStorage.getItem("token")}`
return cfg
})React Query (Server State Done Right)
npm i @tanstack/react-query
const { data, isLoading, error } = useQuery({
queryKey: ["books"],
queryFn: () => fetch("/api/books").then(r => r.json()),
})
const create = useMutation({
mutationFn: b => api.post("/books", b),
onSuccess: () => queryClient.invalidateQueries(["books"]),
})Caching, retries, background refetch and loading states come free - stop hand-rolling them with useEffect.
Key Points
- fetch for learning, Axios for comfort, React Query for production.
- Mutations invalidate queries - UI stays fresh automatically.