@custom-react-hooks/use-fetch

中文文档
2.0.3发布于 2025/09/13MITTypeScriptCommonJS零依赖近 30 天下载 3697

The useFetch hook is a powerful tool for making API requests in React applications. It simplifies the process of fetching data from a URL and handles various advanced features like caching, timeouts, and integration with global state management systems.

原始使用文档
文档目录12 节
  1. Installation
  2. Installing Only Current Hooks
  3. Installing All Hooks
  4. Importing the Hook
  5. Features
  6. Usage
  7. API Reference
  8. Parameters
  9. Returns
  10. Use Cases
  11. Notes
  12. Contributing

useFetch Hook

The useFetch hook is a powerful tool for making API requests in React applications. It simplifies the process of fetching data from a URL and handles various advanced features like caching, timeouts, and integration with global state management systems.

Installation

Installing Only Current Hooks

npm install @custom-react-hooks/use-fetch

or

yarn add @custom-react-hooks/use-fetch

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Certainly! Based on the provided useFetch hook, here are some detailed features that you can include in your documentation:

Importing the Hook

The useFetch hook must be imported using a named import as shown below:

Named Import:

import { useFetch } from '@custom-react-hooks/use-fetch';

This approach ensures that the hook integrates seamlessly into your project, maintaining consistency and predictability in how you use our package.

Features

  • Automatic Data Fetching: The hook initiates a fetch request as soon as the component mounts, making it effortless to load data from APIs or servers. This behavior can be controlled with the manual option for more specific use cases.

  • Manual Fetch Control: Provides the flexibility to manually trigger fetch requests using the fetchData function. This is particularly useful for cases where data needs to be re-fetched based on user interactions or other events.

  • Built-in Loading and Error States: Manages loading and error states internally, simplifying the process of rendering different UI components based on the status of the API request.

  • Configurable Fetch Options: Extends the standard fetch API options, allowing customization of request headers, method, body, and other settings. This makes it versatile for various types of API requests.

  • Timeout Support: Includes a timeout feature, enabling the specification of a maximum time to wait for a response. This helps in handling scenarios where the server response might be delayed.

  • Response Caching: Offers an optional caching mechanism to store and retrieve responses. This reduces redundant network requests, optimizing performance for frequently accessed data.

  • Global State Integration: Allows for the integration with global state management systems by providing an optional setter function. This is useful for updating global states like Redux or Context API with the fetched data.

  • Automatic Cleanup: Handles the cleanup of timeouts and aborts ongoing fetch requests to prevent memory leaks and unwanted side effects, especially important in dynamic and complex applications.

  • Error Handling: Captures and returns errors encountered during the fetch process, facilitating robust error handling and user feedback mechanisms in the application.

  • Flexible Return Types: The hook is generic, making it capable of returning data in any format (e.g., JSON, text), depending on the needs of the application.

  • Server-Side Rendering Compatibility: Designed to be safely used in server-side rendering environments, avoiding errors related to the absence of a window or browser-specific APIs.

Usage

Here's an example of how to use the useFetch hook in a component:

import { useFetch } from '@custom-react-hooks/all';

const FetchComponent = () => {
  const [url, setUrl] = useState('https://jsonplaceholder.typicode.com/users/1');
  const { data, loading, error, fetchData } = useFetch(url, { manual: true });

  const handleChange = (event) => {
    setUrl(event.target.value);
  };

  const handleFetch = () => {
    fetchData();
  };

  return (
    <div>
      <input
        type="text"
        value={url}
        onChange={handleChange}
      />
      <button
        onClick={handleFetch}
        disabled={loading}
      >
        Fetch Data
      </button>

      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {data && (
        <div>
          <p>Data:</p>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default FetchComponent;

In this example, useFetch is used to load data from an API. The component displays the data, a loading state, and any error that might occur. A button is provided to manually trigger the fetch request.

API Reference

Parameters

  • url (string): The URL to fetch data from.
  • options (RequestInit & { manual?: boolean, timeout?: number }, optional): Configuration options for the fetch request. Includes standard fetch options along with manual for manual trigger and timeout for request timeout.
  • cache (Map<string, T> | null, optional): An optional cache object to store and retrieve responses.
  • globalStateSetter ((data: T | null) => void, optional): An optional global state setter function for integration with global state management systems.

Returns

An object containing:

  • data (T | null): The data received from the fetch request.
  • loading (boolean): The loading state of the request.
  • error (Error | null): Any error encountered during the request.
  • fetchData (() => Promise): A function to manually trigger the fetch request.

Use Cases

  • Data Fetching: Load data from an API or server, handling loading states and errors.
  • Caching Responses: Implement caching strategies to reduce redundant network requests.
  • Global State Updates: Update global state (like in Redux or Context API) with fetched data.
  • Polling Mechanism: Implement polling for real-time updates from a server.
  • Conditional Requests: Make API requests based on user actions or component lifecycle.

Notes

  • The useFetch hook is designed to be flexible and can be adapted to fit various fetching requirements.
  • Remember to handle the cleanup of timeouts and abort controllers to avoid memory leaks and unexpected behavior in your components.

Contributing

Contributions to enhance the useFetch hook are welcome. Feel free to submit issues or pull requests to the repository.

版本与发布记录

@custom-react-hooks/use-fetch 共发布 11 个版本,首次发布于 2023/12/02;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.3latest2025/09/131.2 年前
2.0.22025/09/131.2 年前
2.0.12025/09/131.2 年前
1.5.12024/08/182 年前
1.5.02024/08/182 年前
1.4.192023/12/092 年前

关于 @custom-react-hooks/use-fetch 的常见问题

@custom-react-hooks/use-fetch 是什么?

The useFetch hook is a powerful tool for making API requests in React applications. It simplifies the process of fetching data from a URL and handles various advanced features like caching, timeouts, and integration with global state management systems.

如何安装 @custom-react-hooks/use-fetch?

在项目目录运行 npm install @custom-react-hooks/use-fetch,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>=16)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@custom-react-hooks/use-fetch 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@custom-react-hooks/use-fetch 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@custom-react-hooks/use-fetch 可以商用吗?

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

@custom-react-hooks/use-fetch 的下载量有多少?

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

@custom-react-hooks/use-fetch 还在维护吗?

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