React hooks for axios, with built-in support for server side rendering.
- All the axios awesomeness you are familiar with
- Zero configuration, but configurable if needed
- One-line usage
- Super straightforward to use with SSR
npm install axios axios-hooks
axios
is a peer dependency and needs to be installed explicitly
import useAxios from 'axios-hooks'
function App() {
const [{ data, loading, error }, refetch] = useAxios(
'https://api.myjson.com/bins/820fc'
)
if (loading) return <p>Loading...</p>
if (error) return <p>Error!</p>
return (
<div>
<button onClick={refetch}>refetch</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
}
The package exports one default export and named exports:
import useAxios, { configure, loadCache, serializeCache } from 'axios-hooks'
The main React hook to execute HTTP requests.
url|config
The request URL or config object, the same argument accepted byaxios
options
a configuration object containing these keys:manual
False by default. If true, the request is not executed immediately. Useful for non-GET requests that should not be executed when the component renders. Use theexecute
function returned when invoking the hooks to execute the request manually, optionally providing additional arguments toaxios
.
Returns:
[{ data, loading, error, response }, execute]
-
data
The success response data property (for convenient access) -
loading
True if the request is in progress, otherwise False -
error
The error value -
response
The whole success response object -
execute([config])
Function to execute the request manually, bypassing the cache. It optionally accepts the sameconfig
object asaxios
, which is shallow-merged with the config object provided when invoking the hook. Useful to provide arguments to non-GET requests.
Allows to provide custom instances of cache and axios.
Dumps the request-response cache, to use in server side sendering scenarios.
Returns:
Promise<Array>
A serializable representation of the request-response cache ready to be used by loadCache
Populates the cache with serialized data generated by serializeCache
.
cache
The serializable representation of the request-response cache generated byserializeCache
On the client, requests are executed when the component renders using a React useEffect
hook.
This may be undesirable, as in the case of non-GET requests. By using the manual
option you can skip the automatic execution of requests and use the return value of the hook to execute them manually, optionally providing configuration overrides to axios
.
In the example below we use the useAxios
hook twice. Once to load the data when the component renders, and once to submit data updates via a PUT
request configured via the manual
option.
import useAxios from 'axios-hooks'
function App() {
const [{ data: getData, loading: getLoading, error: getError }] = useAxios(
'https://api.myjson.com/bins/820fc'
)
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT'
},
{ manual: true }
)
function updateData() {
executePut({
data: {
...getData,
updatedAt: new Date().toISOString()
}
})
}
if (getLoading || putLoading) return <p>Loading...</p>
if (getError || putError) return <p>Error!</p>
return (
<div>
<button onClick={updateData}>update data</button>
<pre>{JSON.stringify(putData || getData, null, 2)}</pre>
</div>
)
}
Unless provided via the configure
function, axios-hooks
uses as defaults:
axios
- the defaultaxios
package exportcache
- a new instance of the defaultlru-cache
package export, with no arguments
These defaults may not suit your needs:
- you may want a common base url for axios requests
- the default (Infinite) cache size may not be a sensible default
In such cases you can use the configure
function to provide your custom implementation of both.
When
configure
is used, it should be invoked once before any usages of theuseAxios
hook
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 })
axios-hooks
seamlessly supports server side rendering scenarios, by preloading data on the server and providing the data to the client, so that the client doesn't need to reload it.
- the React component tree is rendered on the server
useAxios
HTTP requests are executed on the server- the server code awaits
serializeCache()
in order to obtain a serializable representation of the request-response cache - the server injects a JSON-serialized version of the cache in a
window
global variable - the client hydrates the cache from the global variable before rendering the application using
loadCache
<!-- fragment of the HTML template defining the window global variable -->
<script>
window.__AXIOS_HOOKS_CACHE__ = {{{cache}}}
</script>
// server code for the server side rendering handler
import { serializeCache } from 'axios-hooks'
router.use(async (req, res) => {
const index = fs.readFileSync(`${publicFolder}/index.html`, 'utf8')
const html = ReactDOM.renderToString(<App />)
// wait for axios-hooks HTTP requests to complete
const cache = await serializeCache()
res.send(
index
.replace('{{{html}}}', html)
.replace('{{{cache}}}', JSON.stringify(cache).replace(/</g, '\\u003c'))
)
})
// client side code for the application entry-point
import { loadCache } from 'axios-hooks'
loadCache(window.__AXIOS_HOOKS_CACHE__)
delete window.__AXIOS_HOOKS_CACHE__
ReactDOM.hydrate(<App />, document.getElementById('root'))
axios-hooks depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill.
axios-hooks
is heavily inspired by graphql-hooks,
developed by the awesome people at NearForm.
MIT