Skip to Main ContentSkip to Footer

The Modern Way to Use Promise- Based HTTP Requests: axios-hooks

November 22, 2019

What’s axios-hooks?

You might need to make requests to your own or external API in your React app and you usually needed to use Promises to get the results back, trying to use them inside your React components with the axios library.

Axios-hooks is here to solve this problem with a simpler syntax using the complete power of React Hooks in a few lines of code.

Features

All the axios awesomeness you are familiar with but simplified with Hooks.

  • Zero configuration, but configurable in case it’s needed.
  • One-line usage.
  • Super straightforward to use with server-side rendering.

Installation

To install it with npm:

npm install axios axios-hooks

To install it with Yarn:

yarn add axios axios-hooks

Axios is a peer dependency and needs to be installed explicitly.

How Do I Use It?

It will feel easy, like using useQuery from Apollo React with GraphQL queries.

useAxios

This hook will return three simple elements:

  • data: An object containing the response from the server.
  • loading: Boolean if the request is pending.
  • error: If the response contained an error code with related messages.

You will access the useAxios Hook to do almost every operation and, in some cases, also the configure Hook to define an API-base endpoint URL.

import { configure } from ‘axios-hooks’
import LRU from ‘lru-cache’
import Axios from ‘axios’

const axios = Axios.create({
baseURL: ’https://api.myjson.com/
})

const cache = new LRU({ max: 10 })

configure({ axios, cache })

CodeSandbox React axios Playground

If you want to learn more about Hooks

I have personally read Learn React Hooks when I started using hooks and it helped me understand them to use tools such as useAxios: https://amzn.to/2Y8hoX9

Resources and References


Subscribe to my email list!

If you enjoy my work, you should definitely join my newsletter"Giorat Mails". It’s one email a week with everything interesting I’ve read or found, plus new articles and fresh tutorials.

Sign up for our newsletter