{"id":13484915,"url":"https://github.com/n1ru4l/use-async-effect","last_synced_at":"2025-10-20T01:47:02.882Z","repository":{"id":35017232,"uuid":"196944122","full_name":"n1ru4l/use-async-effect","owner":"n1ru4l","description":"React hook for async effects powered by generator functions.","archived":false,"fork":false,"pushed_at":"2023-03-04T04:20:04.000Z","size":1862,"stargazers_count":197,"open_issues_count":9,"forks_count":8,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-29T22:11:15.145Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/n1ru4l.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"Contributing.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-07-15T07:09:34.000Z","updated_at":"2024-05-08T01:03:45.000Z","dependencies_parsed_at":"2024-01-10T20:10:37.892Z","dependency_job_id":"37b2233d-3767-43a0-bd55-9244ff94427c","html_url":"https://github.com/n1ru4l/use-async-effect","commit_stats":{"total_commits":124,"total_committers":9,"mean_commits":"13.777777777777779","dds":0.4032258064516129,"last_synced_commit":"3fcd547ad98587c108aa67a1dce73caa12c66d72"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/n1ru4l%2Fuse-async-effect","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/n1ru4l%2Fuse-async-effect/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/n1ru4l%2Fuse-async-effect/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/n1ru4l%2Fuse-async-effect/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/n1ru4l","download_url":"https://codeload.github.com/n1ru4l/use-async-effect/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247415973,"owners_count":20935387,"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":[],"created_at":"2024-07-31T17:01:38.690Z","updated_at":"2025-10-20T01:47:02.785Z","avatar_url":"https://github.com/n1ru4l.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# useAsyncEffect\n\n[![npm](https://img.shields.io/npm/v/@n1ru4l/use-async-effect.svg)](https://www.npmjs.com/package/@n1ru4l/use-async-effect)\n[![npm bundle size](https://img.shields.io/bundlephobia/min/@n1ru4l/use-async-effect)](https://bundlephobia.com/result?p=@n1ru4l/use-async-effect)\n[![Dependencies](https://img.shields.io/david/n1ru4l/use-async-effect)](https://www.npmjs.com/package/@n1ru4l/use-async-effect)\n[![NPM](https://img.shields.io/npm/dm/@n1ru4l/use-async-effect.svg)](https://www.npmjs.com/package/@n1ru4l/use-async-effect)\n[![CircleCI](https://img.shields.io/circleci/build/github/n1ru4l/use-async-effect.svg)](https://circleci.com/gh/n1ru4l/use-async-effect)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\nSimple type-safe async effects for React powered by [generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*).\n\n```tsx\nimport React from \"react\";\nimport useAsyncEffect from \"@n1ru4l/use-async-effect\";\n\nconst MyComponent = ({ filter }) =\u003e {\n  const [data, setData] = React.useState(null);\n\n  useAsyncEffect(\n    function* (onCancel, c) {\n      const controller = new AbortController();\n\n      onCancel(() =\u003e controller.abort());\n\n      const data = yield* c(\n        fetch(\"/data?filter=\" + filter, {\n          signal: controller.signal,\n        }).then((res) =\u003e res.json())\n      );\n\n      setData(data);\n    },\n    [filter]\n  );\n\n  return data ? \u003cRenderData data={data} /\u003e : null;\n};\n```\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n- [Install Instructions](#install-instructions)\n- [The problem](#the-problem)\n- [Example](#example)\n  - [Before 😖](#before-)\n  - [After 🤩](#after-)\n- [Usage](#usage)\n  - [Basic Usage](#basic-usage)\n  - [Cancel handler (Cancelling an in-flight `fetch` request)](#cancel-handler-cancelling-an-in-flight-fetch-request)\n  - [Cleanup Handler](#cleanup-handler)\n  - [Setup eslint for `eslint-plugin-react-hooks`](#setup-eslint-for-eslint-plugin-react-hooks)\n  - [TypeScript](#typescript)\n- [API](#api)\n  - [`useAsyncEffect` Hook](#useasynceffect-hook)\n- [Contributing](#contributing)\n- [LICENSE](#license)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n## Install Instructions\n\n`yarn add -E @n1ru4l/use-async-effect`\n\nor\n\n`npm install -E @n1ru4l/use-async-effect`\n\n## The problem\n\nDoing async stuff with `useEffect` clutters your code:\n\n- 😖 You cannot pass an async function to `useEffect`\n- 🤢 You cannot cancel an async function\n- 🤮 You have to manually keep track whether you can set state or not\n\nThis micro library tries to solve this issue by using generator functions:\n\n- ✅ Pass a generator to `useAsyncEffect`\n- ✅ Return cleanup function from generator function\n- ✅ Automatically stop running the generator after the dependency list has changed or the component did unmount\n- ✅ Optional cancelation handling via events e.g. for canceling your `fetch` request with [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Examples)\n\n## Example\n\n### Before 😖\n\n```jsx\nimport React, { useEffect } from \"react\";\n\nconst MyComponent = ({ filter }) =\u003e {\n  const [data, setData] = useState(null);\n\n  useEffect(() =\u003e {\n    let isCanceled = false;\n    const controller = new AbortController();\n\n    const runHandler = async () =\u003e {\n      try {\n        const data = await fetch(\"/data?filter=\" + filter, {\n          signal: controller.signal,\n        }).then((res) =\u003e res.json());\n        if (isCanceled) {\n          return;\n        }\n        setData(data);\n      } catch (err) {}\n    };\n\n    runHandler();\n    return () =\u003e {\n      isCanceled = true;\n      controller.abort();\n    };\n  }, [filter]);\n\n  return data ? \u003cRenderData data={data} /\u003e : null;\n};\n```\n\n### After 🤩\n\n```jsx\nimport React from \"react\";\nimport useAsyncEffect from \"@n1ru4l/use-async-effect\";\n\nconst MyComponent = ({ filter }) =\u003e {\n  const [data, setData] = useState(null);\n\n  useAsyncEffect(\n    function* (onCancel, c) {\n      const controller = new AbortController();\n\n      onCancel(() =\u003e controller.abort());\n\n      const data = yield* c(\n        fetch(\"/data?filter=\" + filter, {\n          signal: controller.signal,\n        }).then((res) =\u003e res.json())\n      );\n\n      setData(data);\n    },\n    [filter]\n  );\n\n  return data ? \u003cRenderData data={data} /\u003e : null;\n};\n```\n\n## Usage\n\nWorks like `useEffect`, but with a generator function.\n\n### Basic Usage\n\n```jsx\nimport React, { useState } from \"react\";\nimport useAsyncEffect from \"@n1ru4l/use-async-effect\";\n\nconst MyDoggoImage = () =\u003e {\n  const [doggoImageSrc, setDoggoImageSrc] = useState(null);\n  useAsyncEffect(function* (_, c) {\n    const { message } = yield* c(\n      fetch(\"https://dog.ceo/api/breeds/image/random\").then((res) =\u003e res.json())\n    );\n    setDoggoImageSrc(message);\n  }, []);\n\n  return doggoImageSrc ? \u003cimg src={doggoImageSrc} /\u003e : null;\n};\n```\n\n[![Edit use-async-effect doggo demo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/use-async-effect-doggo-demo-qrqix?fontsize=14)\n\n### Cancel handler (Cancelling an in-flight `fetch` request)\n\nYou can react to cancels, that might occur while a promise has not resolved yet, by registering a handler via `onCancel`.\nAfter an async operation has been processed, the `onCancel` handler is automatically being unset.\n\n```jsx\nimport React, { useState } from \"react\";\nimport useAsyncEffect from \"@n1ru4l/use-async-effect\";\n\nconst MyDoggoImage = () =\u003e {\n  const [doggoImageSrc, setDoggoImageSrc] = useState(null);\n  useAsyncEffect(function* (onCancel, c) {\n    const abortController = new AbortController();\n    onCancel(() =\u003e abortController.abort());\n    const { message } = yield c(\n      fetch(\"https://dog.ceo/api/breeds/image/random\", {\n        signal: abortController.signal,\n      }).then((res) =\u003e res.json())\n    );\n    setDoggoImageSrc(message);\n  }, []);\n\n  return doggoImageSrc ? \u003cimg src={doggoImageSrc} /\u003e : null;\n};\n```\n\n[![Edit use-async-effect doggo cancel demo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/use-async-effect-doggo-cancel-demo-6rxvd?fontsize=14)\n\n### Cleanup Handler\n\nSimilar to `React.useEffect` you can return a cleanup function from your generator function.\nIt will be called once the effect dependencies change or the component is unmounted.\nPlease take note that the whole generator must be executed before the cleanup handler can be invoked.\nIn case you setup event listeners etc. earlier you will also have to clean them up by specifiying a cancel handler.\n\n```jsx\nimport React, { useState } from \"react\";\nimport useAsyncEffect from \"@n1ru4l/use-async-effect\";\n\nconst MyDoggoImage = () =\u003e {\n  const [doggoImageSrc, setDoggoImageSrc] = useState(null);\n  useAsyncEffect(function* (_, c) {\n    const { message } = yield* c(\n      fetch(\"https://dog.ceo/api/breeds/image/random\").then((res) =\u003e res.json())\n    );\n    setDoggoImageSrc(message);\n\n    const listener = () =\u003e {\n      console.log(\"I LOVE DOGGIES\", message);\n    };\n    window.addEventListener(\"mousemove\", listener);\n    return () =\u003e window.removeEventListener(\"mousemove\", listener);\n  }, []);\n\n  return doggoImageSrc ? \u003cimg src={doggoImageSrc} /\u003e : null;\n};\n```\n\n[![Edit use-async-effect cleanup doggo demo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/use-async-effect-doggo-demo-w1zlh?fontsize=14)\n\n### Setup eslint for `eslint-plugin-react-hooks`\n\nYou need to configure the `react-hooks/exhaustive-deps` plugin to treat `useAsyncEffect` as a hook with dependencies.\n\nAdd the following to your eslint config file:\n\n```json\n{\n  \"rules\": {\n    \"react-hooks/exhaustive-deps\": [\n      \"warn\",\n      {\n        \"additionalHooks\": \"useAsyncEffect\"\n      }\n    ]\n  }\n}\n```\n\n### TypeScript\n\nWe expose a helper function for TypeScript that allows interferring the correct Promise resolve type. It uses some type-casting magic under the hood and requires you to use the `yield*` keyword instead of the `yield` keyword.\n\n```tsx\nuseAsyncEffect(function* (setErrorHandler, c) {\n  const numericValue = yield* c(Promise.resolve(123));\n  // type of numericValue is number 🎉\n});\n```\n\n## API\n\n### `useAsyncEffect` Hook\n\nRuns a effect that includes async operations. The effect ins cancelled upon dependency change/unmount.\n\n```ts\nfunction useAsyncEffect(\n  createGenerator: (\n    setCancelHandler: (\n      onCancel?: null | (() =\u003e void),\n      onCancelError?: null | ((err: Error) =\u003e void)\n    ) =\u003e void,\n    cast: \u003cT\u003e(promise: Promise\u003cT\u003e) =\u003e Generator\u003cPromise\u003cT\u003e, T\u003e\n  ) =\u003e Iterator\u003cany, any, any\u003e,\n  deps?: React.DependencyList\n): void;\n```\n\n## Contributing\n\nPlease check our contribution guides [Contributing](https://github.com/n1ru4l/use-async-effect/blob/master/Contributing.md).\n\n## LICENSE\n\n[MIT](https://github.com/n1ru4l/use-async-effect/blob/master/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fn1ru4l%2Fuse-async-effect","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fn1ru4l%2Fuse-async-effect","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fn1ru4l%2Fuse-async-effect/lists"}