🪝
Axios Cache Hooks
Axios Cache Hooks
is the faster, simple and efficient way to use Axios inside React applications.
Table of Contents
Installing
npm install axios axios-cache-interceptor axios-cache-hooks
yarn add axios axios-cache-interceptor axios-cache-hooks
import { createAxiosHooks } from 'axios-cache-hooks';
const { createAxiosHooks } = require('axios-cache-hooks');
const { createAxiosHooks } = window.axiosCacheHooks;
<script
crossorigin
src="https://cdn.jsdelivr.net/npm/axios-cache-hooks@latest/dist/index.umd.js"
></script>
Url Import
import { createAxiosHooks } from 'https://cdn.skypack.dev/axios-cache-hooks@latest';
Getting Started
Axios Cache Hooks is a super effective and performant way to use Axios calls inside React
applications. It is very performant because it deeply uses (and only works with)
Axios (6.7Kb)
and
Axios Cache Interceptor (4.2Kb)
under the
hood.
// http.ts
import Axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
import { createAxiosHooks } from 'axios-cache-hooks';
export const axios = setupCache(Axios);
export const { useQuery, useMutation } = createAxiosHooks();
/** Returns an user by his name */
export function getUser(name: string, config?: AxiosRequestConfig): Promise<User> {
return axios.get<User>(`users/find-by-name/${name}`, config);
}
// component.tsx
import { useQuery, getUser } from './http';
export const UserAge = ({ username }) => {
// This will share cache between ALL components that uses the same query and parameters.
const [user, { loading, error }] = useQuery(getUser, username);
return (
<Layout>
<p>{loading ? 'loading...' : user.age}</p>
</Layout>
);
};
Documentation
This package is just a "bridge" between Axios with Cache and React. Please read the
Axios Cache Interceptor
documentation for any cache issue.
This package is so small that every documentation is available in the form of TSDoc
. You
can start by importing createAxiosHooks
and using the returned hooks.
How it works
Basically, this package calls the provided http function on every draw, this is fine
because you can only use this hook with axios-cache-interceptor
which caches very
effectively axios request, only allowing needed axios request to go through network.
By extracting you request functions into dedicated functions, like the getUser
above,
you'll enable caching requests at a component level, even for your micro-frontend setup.
This works flawlessly because Axios Cache Interceptor
has a concept of
Request IDs
that defines
which requests are the same or not.
If you still have any questions, please feel free to create an issue and i'll be happy to help (and even improve this readme).
Compatibility
This package is dependent of AxiosCacheInterceptor@>=0.8
and Axios@>=0.28
because of this PR.
License
Licensed under the MIT. See LICENSE
for more informations.