百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
U

use-async-effect

> 编程语言
开源

基于生成器函数的异步效果的 React 钩子。

197 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

基于生成器函数的异步效果的 React 钩子。

useAsyncEffect

Simple type-safe async effects for React powered by generator functions.

typescript
import React from "react";
import useAsyncEffect from "@n1ru4l/use-async-effect";

const MyComponent = ({ filter }) => {
  const [data, setData] = React.useState(null);

  useAsyncEffect(
    function* (onCancel, c) {
      const controller = new AbortController();

      onCancel(() => controller.abort());

      const data = yield* c(
        fetch("/data?filter=" + filter, {
          signal: controller.signal,
        }).then((res) => res.json())
      );

      setData(data);
    },
    [filter]
  );

  return data ?  : null;
};
  • Install Instructions
  • The problem
  • Example
    • Before
    • After
  • Usage
    • Basic Usage
    • Cancel handler (Cancelling an in-flight fetch request)
    • Cleanup Handler
    • Setup eslint for eslint-plugin-react-hooks
    • TypeScript
  • API
    • useAsyncEffect Hook
  • Contributing
  • LICENSE

Install Instructions

yarn add -E @n1ru4l/use-async-effect

or

npm install -E @n1ru4l/use-async-effect

The problem

Doing async stuff with useEffect clutters your code:

  • You cannot pass an async function to useEffect
  • You cannot cancel an async function
  • You have to manually keep track whether you can set state or not

This micro library tries to solve this issue by using generator functions:

  • ✅ Pass a generator to useAsyncEffect
  • ✅ Return cleanup function from generator function
  • ✅ Automatically stop running the generator after the dependency list has changed or the component did unmount
  • ✅ Optional cancelation handling via events e.g. for canceling your fetch request with AbortController

Example

Before

…

After

javascript
import React from "react";
import useAsyncEffect from "@n1ru4l/use-async-effect";

const MyComponent = ({ filter }) => {
  const [data, setData] = useState(null);

  useAsyncEffect(
    function* (onCancel, c) {
      const controller = new AbortController();

      onCancel(() => controller.abort());

      const data = yield* c(
        fetch("/data?filter=" + filter, {
          signal: controller.signal,
        }).then((res) => res.json())
      );

      setData(data);
    },
    [filter]
  );

  return data ?  : null;
};

Usage

Works like useEffect, but with a generator function.

Basic Usage

javascript
import React, { useState } from "react";
import useAsyncEffect from "@n1ru4l/use-async-effect";

const MyDoggoImage = () => {
  const [doggoImageSrc, setDoggoImageSrc] = useState(null);
  useAsyncEffect(function* (_, c) {
    const { message } = yield* c(
      fetch("https://dog.ceo/api/breeds/image/random").then((res) => res.json())
    );
    setDoggoImageSrc(message);
  }, []);

  return doggoImageSrc ?  : null;
};

Cancel handler (Cancelling an in-flight fetch request)

You can react to cancels, that might occur while a promise has not resolved yet, by registering a handler via onCancel. After an async operation has been processed, the onCancel handler is automatically being unset.

javascript
import React, { useState } from "react";
import useAsyncEffect from "@n1ru4l/use-async-effect";

const MyDoggoImage = () => {
  const [doggoImageSrc, setDoggoImageSrc] = useState(null);
  useAsyncEffect(function* (onCancel, c) {
    const abortController = new AbortController();
    onCancel(() => abortController.abort());
    const { message } = yield c(
      fetch("https://dog.ceo/api/breeds/image/random", {
        signal: abortController.signal,
      }).then((res) => res.json())
    );
    setDoggoImageSrc(message);
  }, []);

  return doggoImageSrc ?  : null;
};

Cleanup Handler

Similar to React.useEffect you can return a cleanup function from your generator function. It will be called once the effect dependencies change or the component is unmounted. Please take note that the whole generator must be executed before the cleanup handler can be invoked. In case you setup event listeners etc. earlier you will also have to clean them up by specifiying a cancel handler.

…

Setup eslint for eslint-plugin-react-hooks

You need to configure the react-hooks/exhaustive-deps plugin to treat useAsyncEffect as a hook with dependencies.

Add the following to your eslint config file:

json
{
  "rules": {
    "react-hooks/exhaustive-deps": [
      "warn",
      {
        "additionalHooks": "useAsyncEffect"
      }
    ]
  }
}

TypeScript

We 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.

typescript
useAsyncEffect(function* (setErrorHandler, c) {
  const numericValue = yield* c(Promise.resolve(123));
  // type of numericValue is number 
});

API

useAsyncEffect Hook

Runs a effect that includes async operations. The effect ins cancelled upon dependency change/unmount.

typescript
function useAsyncEffect(
  createGenerator: (
    setCancelHandler: (
      onCancel?: null | (() => void),
      onCancelError?: null | ((err: Error) => void)
    ) => void,
    cast: (promise: Promise) => Generator, T>
  ) => Iterator,
  deps?: React.DependencyList
): void;

Contributing

Please check our contribution guides Contributing.

LICENSE

MIT.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言