REST APIs: Fetch, Axios and React Query

Harry · 28 Sep 2026 · 1 views
Log in to track your progress and mark lessons complete.

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.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in