@closeio/use-abortable-effect

中文文档
1.0.0发布于 2020/06/18MITESM + CJS零依赖近 30 天下载 4.7万

Super simple React hook for running abortable effects

原始使用文档
文档目录8 节
  1. Install
  2. Benefits
  3. API differences over useEffect
  4. Usage
  5. Abortable fetch requests
  6. Arbitrary computation that can be aborted
  7. Custom cleanup function
  8. License

use-abortable-effect

NPM JavaScript Style Guide

Super simple React hook for running abortable effects based on the AbortController API.

Check the live DEMO.

Interested in working on projects like this? Close is looking for great engineers to join our team!

Install

yarn add @closeio/use-abortable-effect

Benefits

  • Extremely lightweight (less than 500B minzipped).
  • It uses the AbortController API and it is compatible with the fetch API.
  • If a browser does not support the AbortController API then the hook behaves exactly like a regular useEffect hook. See Can I Use for browser support overview.
  • No other 3rd-party dependencies.

API differences over useEffect

  • API is compatible with useEffect, where the effect function you pass-in accepts an AbortSignal instance as a param and you can return a cleanup function that accepts an AbortController instance.
  • Supports abortable fetch requests.
  • Supports running custom operations/computations that can be easily aborted.
  • Auto-aborts effects on re-run (or component unmount), unless you provide a custom cleanup function.
useEffect(() => {
  // do something

  return () => {
    /* cleanup */
  };
}, [deps]);

const abortControllerRef = useAbortableEffect(
  (abortSignal) => {
    // do something

    return (abortController) => {
      /* do cleanup, you should probably abort */
    };
  },
  [deps],
);

Usage

Abortable fetch requests

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyAbortableFetchComponent() {
  const abortControllerRef = useAbortableEffect((abortSignal) =>
    fetch(url, { signal: abortSignal })
      .then(/* … */)
      .catch((rejection) => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      }),
  );

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

Arbitrary computation that can be aborted

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyAbortableComputationComponent() {
  const abortControllerRef = useAbortableEffect(abortSignal => {
    new Promise((resolve, reject) => {
      // Should be a DOMException per spec.
      const abortRejection = new DOMException(
        'Calculation aborted by the user',
        'AbortError',
      );

      // Handle when abort was requested before starting the computation.
      if (abortSignal.aborted) {
        return reject(abortRejection);
      }

      // This simulates an expensive computation.
      const timeout = setTimeout(() => resolve(1), 5000);

      // Listen for abort request.
      abortSignal.addEventListener('abort', () => {
        clearTimeout(timeout);
        reject(abortRejection);
      });
    })
      .then(/* … */)
      .catch(rejection => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      }),
  });

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

Custom cleanup function

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyCustomCleanupComponent() {
  const [gotAborted, setGotAborted] = useState(false);

  const abortControllerRef = useAbortableEffect((abortSignal) => {
    fetch(url, { signal: abortSignal })
      .then(/* … */)
      .catch((rejection) => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      });

    // Just return a function like in `useEffect`, with the difference that you
    // get the abort controller (not a ref) as a param.
    return (controller) => {
      controller.abort();
      setGotAborted(true);
    };
  });

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

License

MIT © Close

版本与发布记录

@closeio/use-abortable-effect 共发布 1 个版本,首次发布于 2020/06/18;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0latest2020/06/186 年前

关于 @closeio/use-abortable-effect 的常见问题

@closeio/use-abortable-effect 是什么?

Super simple React hook for running abortable effects

如何安装 @closeio/use-abortable-effect?

在项目目录运行 npm install @closeio/use-abortable-effect,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=16.8.0)、react-dom(>=16.8.0)、prop-types(^15.5.4)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@closeio/use-abortable-effect 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/closeio__use-abortable-effect 是否存在。

@closeio/use-abortable-effect 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@closeio/use-abortable-effect 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=8。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@closeio/use-abortable-effect 可以商用吗?

@closeio/use-abortable-effect 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@closeio/use-abortable-effect 的下载量有多少?

根据 npm 官方下载统计,@closeio/use-abortable-effect 在 2026/10/10 – 2026/11/08 这 30 天内被下载 47,460 次,日均约 1,582 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@closeio/use-abortable-effect 还在维护吗?

最新版本 1.0.0 发布于 2020/06/18(6 年前);至今共发布 1 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/06/18。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。