{"id":13468639,"url":"https://github.com/simoneb/axios-hooks","last_synced_at":"2025-05-13T15:12:43.285Z","repository":{"id":37800849,"uuid":"171029910","full_name":"simoneb/axios-hooks","owner":"simoneb","description":"🦆 React hooks for axios","archived":false,"fork":false,"pushed_at":"2025-05-01T14:47:11.000Z","size":5188,"stargazers_count":1895,"open_issues_count":5,"forks_count":130,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-05-01T15:40:17.468Z","etag":null,"topics":["axios","hooks","react"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/simoneb.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-16T17:16:38.000Z","updated_at":"2025-05-01T14:47:13.000Z","dependencies_parsed_at":"2023-02-12T23:45:51.402Z","dependency_job_id":"7eac9374-5da6-4f7d-9788-fc0d456675f9","html_url":"https://github.com/simoneb/axios-hooks","commit_stats":{"total_commits":1335,"total_committers":25,"mean_commits":53.4,"dds":"0.45318352059925093","last_synced_commit":"85b7bf011b8f0e90e8b098d463db872d6cd6b6bc"},"previous_names":[],"tags_count":89,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simoneb%2Faxios-hooks","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simoneb%2Faxios-hooks/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simoneb%2Faxios-hooks/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/simoneb%2Faxios-hooks/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/simoneb","download_url":"https://codeload.github.com/simoneb/axios-hooks/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253969266,"owners_count":21992264,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["axios","hooks","react"],"created_at":"2024-07-31T15:01:15.494Z","updated_at":"2025-05-13T15:12:38.270Z","avatar_url":"https://github.com/simoneb.png","language":"JavaScript","readme":"\u003e The license of this software has changed to AWISC - Anti War ISC license\n\n# axios-hooks\n\n[![ci](https://github.com/simoneb/axios-hooks/actions/workflows/ci.yml/badge.svg)](https://github.com/simoneb/axios-hooks/actions/workflows/ci.yml)\n[![codecov](https://codecov.io/gh/simoneb/axios-hooks/branch/master/graph/badge.svg)](https://codecov.io/gh/simoneb/axios-hooks)\n[![npm version](https://badge.fury.io/js/axios-hooks.svg)](https://badge.fury.io/js/axios-hooks)\n[![bundlephobia](https://badgen.net/bundlephobia/minzip/axios-hooks)](https://bundlephobia.com/result?p=axios-hooks)\n\nReact hooks for [axios], with built-in support for server side rendering.\n\n## Features\n\n- All the [axios] awesomeness you are familiar with\n- Zero configuration, but configurable if needed\n- One-line usage\n- Super straightforward to use with SSR\n\n## Installation\n\n`npm install axios axios-hooks`\n\n\u003e `axios` is a peer dependency and needs to be installed explicitly\n\n## Version information\n\n- `axios-hooks@5.x` is compatible with `axios@1.x`\n- `axios-hooks@4.x` and below are compatible with `axios@0.x`\n\n## Quick Start\n\n[![Edit axios-hooks Quick Start](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/2oxrlq8rjr)\n\n```js\nimport useAxios from 'axios-hooks'\n\nfunction App() {\n  const [{ data, loading, error }, refetch] = useAxios(\n    'https://reqres.in/api/users?delay=1'\n  )\n\n  if (loading) return \u003cp\u003eLoading...\u003c/p\u003e\n  if (error) return \u003cp\u003eError!\u003c/p\u003e\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={refetch}\u003erefetch\u003c/button\u003e\n      \u003cpre\u003e{JSON.stringify(data, null, 2)}\u003c/pre\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## Documentation\n\n### API\n\n- [useAxios](#useaxiosurlconfig-options)\n- [configure](#configure-cache-axios-defaultoptions-)\n- [serializeCache](#serializeCache)\n- [loadCache](#loadcachecache)\n- [makeUseAxios](#makeuseaxios-cache-axios-defaultoptions-)\n\n### Examples\n\n- [Quick start](https://codesandbox.io/s/2oxrlq8rjr)\n- [Manual request](https://codesandbox.io/s/axioshooks-manual-request-bq9w4)\n- [Error handling](https://codesandbox.io/s/axios-hooks-error-handling-gvi41)\n- [Authentication and token refresh](https://codesandbox.io/s/axios-hooks-authentication-zyeyh)\n- [Caching](https://codesandbox.io/s/axios-hooks-caching-nm62v)\n- [Using makeUseAxios](https://codesandbox.io/s/axios-hooks-makeuseaxios-kfuym)\n- [Configuration](https://codesandbox.io/s/oqvxw6mpyq)\n- [Pagination](https://codesandbox.io/s/axios-hooks-pagination-1wk3u)\n- [Infinite scrolling](https://codesandbox.io/s/axios-hooks-infinite-scrolling-42nw6)\n- [Request chaining](https://codesandbox.io/s/axios-hooks-request-chaining-wn12l)\n- [Options change detection](https://codesandbox.io/s/axios-hooks-options-change-v23tl)\n- [react-native](https://snack.expo.io/@simoneb/axios-hooks-react-native)\n- [With react-sortable-hoc](https://codesandbox.io/s/axios-hooks-react-sortable-hoc-eo3oy)\n- [With react-router](https://codesandbox.io/s/axios-hooks-react-router-26iwm)\n\n### Guides\n\n- [Refresh Behavior](#refresh-behavior)\n- [Configuration](#configuration)\n- [Manual Requests](#manual-requests)\n- [Manual Cancellation](#manual-cancellation)\n- [Server Side Rendering](#server-side-rendering)\n- [Multiple Hook Instances](#multiple-hook-instances)\n\n## API\n\nThe package exports one default export and named exports:\n\n```js\nimport useAxios, {\n  configure,\n  loadCache,\n  serializeCache,\n  makeUseAxios\n} from 'axios-hooks'\n```\n\n### useAxios(url|config, options)\n\nThe main React hook to execute HTTP requests.\n\n- `url|config` - The request URL or [config](https://github.com/axios/axios#request-config) object, the same argument accepted by `axios`.\n- `options` - An options object.\n  - `manual` ( `false` ) - If true, the request is not executed immediately. Useful for non-GET requests that should not be executed when the component renders. Use the `execute` function returned when invoking the hook to execute the request manually.\n  - `useCache` ( `true` ) - Allows caching to be enabled/disabled for the hook. It doesn't affect the `execute` function returned by the hook.\n  - `ssr` ( `true` ) - Enables or disables SSR support\n  - `autoCancel` ( `true` ) - Enables or disables automatic cancellation of pending requests whether it be\n    from the automatic hook request or from the `manual` execute method\n\n\u003e [!IMPORTANT]  \n\u003e Default caching behavior can interfere with test isolation. Read the [testing](#testing) section for more information.\n\n**Returns**\n\n`[{ data, loading, error, response }, execute, manualCancel]`\n\n- `data` - The [success response](https://github.com/axios/axios#response-schema) data property (for convenient access).\n- `loading` - True if the request is in progress, otherwise False.\n- `error` - The [error](https://github.com/axios/axios#handling-errors) value\n- `response` - The whole [success response](https://github.com/axios/axios#response-schema) object.\n\n- `execute([config[, options]])` - A function to execute the request manually, bypassing the cache by default.\n\n  - `config` - Same `config` object as `axios`, which is _shallow-merged_ with the config object provided when invoking the hook. Useful to provide arguments to non-GET requests.\n  - `options` - An options object.\n    - `useCache` ( `false` ) - Allows caching to be enabled/disabled for this \"execute\" function.\n\n  **Returns**\n\n  A promise containing the response. If the request is unsuccessful, the promise rejects and the rejection must be handled manually.\n\n- `manualCancel()` - A function to cancel outstanding requests manually.\n\n### configure({ cache, axios, defaultOptions })\n\nAllows to provide custom instances of cache and axios and to override the default options.\n\n- `cache` An instance of [lru-cache](https://github.com/isaacs/node-lru-cache), or `false` to disable the cache\n- `axios` An instance of [axios](https://github.com/axios/axios#creating-an-instance)\n- `defaultOptions` An object overriding the default Hook options. It will be merged with the default options.\n\n### serializeCache()\n\nDumps the request-response cache, to use in server side rendering scenarios.\n\n**Returns**\n\n`Promise\u003cArray\u003e` A serializable representation of the request-response cache ready to be used by `loadCache`\n\n### loadCache(cache)\n\nPopulates the cache with serialized data generated by `serializeCache`.\n\n- `cache` The serializable representation of the request-response cache generated by `serializeCache`\n\n### makeUseAxios({ cache, axios, defaultOptions })\n\nCreates an instance of the `useAxios` hook configured with the supplied cache, axios instance and default options.\n\n- `cache` An instance of [lru-cache](https://github.com/isaacs/node-lru-cache), or `false` to disable the cache\n- `axios` An instance of [axios](https://github.com/axios/axios#creating-an-instance)\n- `defaultOptions` An object overriding the default Hook options. It will be merged with the default options.\n\n**Returns**\n\nAn instance of `useAxios` React Hook which will always use the provided cache and axios instance.\n\nThe returned value, besides being a function that can be used as a React Hook, also contains the properties:\n\n- `resetConfigure`\n- `configure`\n- `loadCache`\n- `serializeCache`\n\nwhich are the same as the package's named exports but limited to the `useAxios` instance returned by `makeUseAxios`.\n\n## Refresh Behavior\n\nThe arguments provided to `useAxios(config[,options])` are watched for changes and compared using deep object comparison.\n\nWhen they change, if the configuration allows a request to be fired (e.g. `manual:false`), any pending request is canceled and a new request is triggered, to avoid automatic cancellation you should use `autoCancel:false` option\n\nBecause of this, it's important to make sure that the arguments to `useAxios` preserve deep equality across component renders. This is often the case unless functions (e.g. axios transformers) are provided to a configuration object. In that case, those functions need to be memoized or they will trigger a request execution at each render, leading to an infinite loop.\n\n## Configuration\n\nUnless provided via the `configure` function, `axios-hooks` uses as defaults:\n\n- `axios` - the default `axios` package export\n- `cache` - a new instance of the default `lru-cache` package export, with no arguments\n- `defaultOptions` - `{ manual: false, useCache: true, ssr: true, autoCancel: true }`\n\nThese defaults may not suit your needs, for example:\n\n- you may want a common base url for axios requests\n- the default (Infinite) cache size may not be a sensible default\n- you want to disable caching altogether\n\nIn such cases you can use the `configure` function to provide your custom implementation of both.\n\n\u003e When `configure` is used, it should be invoked once before any usages of the `useAxios` hook\n\n### Example\n\n[![Edit axios-hooks configuration example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/oqvxw6mpyq)\n\n```js\nimport { configure } from 'axios-hooks'\nimport LRU from 'lru-cache'\nimport Axios from 'axios'\n\nconst axios = Axios.create({\n  baseURL: 'https://reqres.in/api'\n})\n\nconst cache = new LRU({ max: 10 })\n\nconfigure({ axios, cache })\n```\n\n## Manual Requests\n\nOn the client, requests are executed when the component renders using a React `useEffect` hook.\n\nThis 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`.\n\n### Example\n\nIn 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.\n\n[![Edit axios-hooks Manual Request](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/axioshooks-manual-request-bq9w4?fontsize=14)\n\n```js\nimport useAxios from 'axios-hooks'\n\nfunction App() {\n  const [{ data: getData, loading: getLoading, error: getError }] = useAxios(\n    'https://reqres.in/api/users/1'\n  )\n\n  const [{ data: putData, loading: putLoading, error: putError }, executePut] =\n    useAxios(\n      {\n        url: 'https://reqres.in/api/users/1',\n        method: 'PUT'\n      },\n      { manual: true }\n    )\n\n  function updateData() {\n    executePut({\n      data: {\n        ...getData,\n        updatedAt: new Date().toISOString()\n      }\n    })\n  }\n\n  if (getLoading || putLoading) return \u003cp\u003eLoading...\u003c/p\u003e\n  if (getError || putError) return \u003cp\u003eError!\u003c/p\u003e\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={updateData}\u003eupdate data\u003c/button\u003e\n      \u003cpre\u003e{JSON.stringify(putData || getData, null, 2)}\u003c/pre\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## Manual Cancellation\n\nThe cancellation method can be used to cancel an outstanding request whether it be\nfrom the automatic hook request or from the `manual` execute method.\n\n### Example\n\nIn the example below we use the `useAxios` hook with its automatic and manual requests.\nWe can call the cancellation programmatically or via controls.\n\n```js\nfunction App() {\n  const [pagination, setPagination] = useState({})\n  const [{ data, loading }, refetch, cancelRequest] = useAxios({\n    url: '/users?delay=5',\n    params: { ...pagination }\n  })\n\n  const handleFetch = () =\u003e {\n    setPagination({ per_page: 2, page: 2 })\n  }\n\n  const externalRefetch = async () =\u003e {\n    try {\n      await refetch()\n    } catch (e) {\n      // Handle cancellation\n    }\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={handleFetch}\u003erefetch\u003c/button\u003e\n      \u003cbutton onClick={externalRefetch}\u003eExternal Refetch\u003c/button\u003e\n      \u003cbutton disabled={!loading} onClick={cancelRequest}\u003e\n        Cancel Request\n      \u003c/button\u003e\n      {loading \u0026\u0026 \u003cp\u003e...loading\u003c/p\u003e}\n      \u003cpre\u003e{JSON.stringify(data, null, 2)}\u003c/pre\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## Server Side Rendering\n\n`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.\n\n### How it works\n\n1. the React component tree is rendered on the server\n2. `useAxios` HTTP requests are executed on the server\n3. the server code awaits `serializeCache()` in order to obtain a serializable representation of the request-response cache\n4. the server injects a JSON-serialized version of the cache in a `window` global variable\n5. the client hydrates the cache from the global variable before rendering the application using `loadCache`\n\n### Example\n\n[![Edit axios-hooks SSR example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/v83l3mjq57)\n\n```html\n\u003c!-- fragment of the HTML template defining the window global variable --\u003e\n\n\u003cscript\u003e\n  window.__AXIOS_HOOKS_CACHE__ = {{{cache}}}\n\u003c/script\u003e\n```\n\n```js\n// server code for the server side rendering handler\n\nimport { serializeCache } from 'axios-hooks'\n\nrouter.use(async (req, res) =\u003e {\n  const index = fs.readFileSync(`${publicFolder}/index.html`, 'utf8')\n  const html = ReactDOM.renderToString(\u003cApp /\u003e)\n\n  // wait for axios-hooks HTTP requests to complete\n  const cache = await serializeCache()\n\n  res.send(\n    index\n      .replace('{{{html}}}', html)\n      .replace('{{{cache}}}', JSON.stringify(cache).replace(/\u003c/g, '\\\\u003c'))\n  )\n})\n```\n\n```js\n// client side code for the application entry-point\n\nimport { loadCache } from 'axios-hooks'\n\nloadCache(window.__AXIOS_HOOKS_CACHE__)\n\ndelete window.__AXIOS_HOOKS_CACHE__\n\nReactDOM.hydrate(\u003cApp /\u003e, document.getElementById('root'))\n```\n\n## Multiple Hook Instances\n\nSometimes it is necessary to communicate with different APIs or use different caching strategies for different HTTP interactions.\n\n[`makeUseAxios`](#makeuseaxios-cache-axios) allows to create multiple instances of the `useAxios` React Hook which can be configured and managed independently.\n\nIn other words, `makeUseAxios` is a factory of `useAxios`, which returns a React Hook configured against the provided `axios` or `cache` instances.\n\n\u003e This feature can also be used to create a single pre configured React Hook instance as an alternative to the global `configure` feature\n\n### Example\n\n[![Edit axios-hooks makeUseAxios](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/axios-hooks-quick-start-kfuym)\n\n```js\nimport axios from 'axios'\nimport { makeUseAxios } from 'axios-hooks'\n\nconst useAxios = makeUseAxios({\n  axios: axios.create({ baseURL: 'https://reqres.in/api' })\n})\n\nfunction App() {\n  const [{ data, loading, error }, refetch] = useAxios('/users?delay=1')\n\n  if (loading) return \u003cp\u003eLoading...\u003c/p\u003e\n  if (error) return \u003cp\u003eError!\u003c/p\u003e\n\n  return (\n    \u003cdiv\u003e\n      \u003cbutton onClick={refetch}\u003erefetch\u003c/button\u003e\n      \u003cpre\u003e{JSON.stringify(data, null, 2)}\u003c/pre\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## Testing\n\nTesting components that make use of the `useAxios` hook are susceptible to test isolation leakage because of default caching behavior. The following snippets can be used to disable caching while testing:\n\n### react-testing-library\n\n```js\nbeforeAll(() =\u003e {\n  useAxios.configure({ cache: false })\n})\n```\n\n## Promises\n\naxios-hooks depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).\nIf your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).\n\n## Credits\n\n`axios-hooks` is heavily inspired by [graphql-hooks](https://github.com/nearform/graphql-hooks),\ndeveloped by the awesome people at [NearForm](https://github.com/nearform).\n\n## License\n\nMIT\n\n[axios]: https://github.com/axios/axios\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimoneb%2Faxios-hooks","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsimoneb%2Faxios-hooks","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsimoneb%2Faxios-hooks/lists"}