npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zero-bits/hooks

v1.5.0

Published

Zero-Bits React Hooks

Downloads

614

Readme

@zero-bits/hooks

@zero-bits/hooks 是一个基于 alova 封装的 React 请求 Hook 库。它提供了类似 React Query 风格的 API,具有高度的灵活性和扩展性,可以无缝接入任何基于 Promise 的请求库(如 axios、Taro request 等)。

安装

npm install @zero-bits/hooks alova
# 或者
yarn add @zero-bits/hooks alova
# 或者
pnpm add @zero-bits/hooks alova

核心特性

  • 🚀 请求库无关:底层依赖可以通过适配器接入任何支持 Promise 的请求工具。
  • 🔄 声明式查询 (useQuery):支持 React Query 风格的依赖数组,依赖变化自动重新请求。
  • ⚡️ 命令式修改 (useMutation):提供极简的 API 进行 POST/PUT/DELETE 等操作。
  • 🛠 内置数据转换:支持通过 fieldMap 自动提取统一响应结构中的 codedatamessage 字段。
  • 🎨 完整的生命周期:提供 onSuccessonErroronComplete 以及 onCompleted(仅获取数据)等回调。
  • 🛡 强类型支持:使用 TypeScript 编写,提供完整的类型推导。

快速开始

1. 初始化 Hooks

首先,通过 createRequestHooks 工厂函数创建你的专属请求 Hooks。你可以传入 axios 实例或任何包含 request 方法的对象。

import { createRequestHooks } from '@zero-bits/hooks';
import axios from 'axios';

// 1. 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: 'https://api.example.com',
});

// 2. 初始化 Hooks
// 你也可以通过 config.fieldMap 来自定义响应字段映射
export const { useQuery, useMutation, alovaInst } = createRequestHooks(axiosInstance, {
  fieldMap: {
    code: 'code',       // 状态码字段
    data: 'data',       // 数据字段
    message: 'message', // 提示信息字段
  },
});

2. 使用 useQuery (数据查询)

useQuery 适用于 GET 请求。它支持依赖数组,当依赖项发生变化时,会自动重新发起请求。

import React, { useState } from 'react';
import { useQuery } from './request'; // 引入上面创建的 hooks

function TodoList() {
  const [status, setStatus] = useState('all');

  // React Query 风格:第一项为 URL,后续项为依赖项。依赖项变化自动触发请求
  const { data, loading, error, send } = useQuery(['/todos', status], {
    params: { status },
    // debounce: 500,     // 支持防抖
    // immediate: true,   // 是否组件挂载时立即请求(默认 true)
    // enable: !!status,  // 是否允许请求,可用于依赖请求
    onCompleted: (res) => {
      console.log('数据请求成功', res);
    }
  });

  if (loading) return <div>加载中...</div>;
  if (error) return <div>请求出错了!</div>;

  return (
    <div>
      <button onClick={() => setStatus('completed')}>完成的</button>
      <ul>
        {data?.map(todo => <li key={todo.id}>{todo.title}</li>)}
      </ul>
    </div>
  );
}

3. 使用 useMutation (数据修改)

useMutation 适用于 POST/PUT/DELETE 等非幂等请求,通常需要手动触发(通过调用 send 方法)。

import React from 'react';
import { useMutation } from './request';

function AddTodo() {
  // 基本用法:传入 URL,默认方法为 POST
  const { send: addTodo, loading } = useMutation('/todos');

  // 高阶用法:根据业务入参动态构建请求配置
  const { send: updateTodo, loading: updating } = useMutation(
    (id: string, title: string) => ({
      url: `/todos/${id}`,
      method: 'PUT',
      data: { title }
    }),
    {
      onSuccess: () => {
        alert('更新成功!');
      }
    }
  );

  const handleAdd = async () => {
    try {
      // payload 会作为 data 传递 (针对 POST/PUT/PATCH 请求)
      await addTodo({ title: 'New Task' });
      alert('添加成功!');
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div>
      <button onClick={handleAdd} disabled={loading}>
        {loading ? '保存中...' : '添加任务'}
      </button>
    </div>
  );
}

API 参考

createRequestHooks(instance, config?)

| 参数 | 类型 | 说明 | | --- | --- | --- | | instance | Function \| Object | 请求执行器,可以是 axios 实例,或者 Taro 的 request 实例,或者任何包含 request 方法的对象。 | | config | RequestHooksConfig | 可选配置对象。 |

RequestHooksConfig

interface RequestHooksConfig {
  fieldMap?: {
    code?: string;    // 默认 'code'
    data?: string;    // 默认 'data'
    message?: string; // 默认 'message'
  }
}

useQuery 参数签名

useQuery 支持多种形式的传参:

  1. 数组传参 (支持依赖项监听): useQuery([url, ...deps], options)
  2. 字符串传参 (仅挂载时请求一次): useQuery(url, options)
  3. 函数构建器 (动态生成请求配置): useQuery(() => RequestConfig, options)

QueryOptions 配置项:

  • immediate (boolean): 是否在挂载时立即执行,默认为 true
  • enable (boolean): 只有为 true 时才允许请求(用于条件查询)。
  • debounce (number): 请求防抖时间(毫秒)。
  • initData (any): 初始占位数据。
  • onSuccess, onError, onComplete, onCompleted: 生命周期回调。

useMutation 参数签名

  1. 字符串传参: useMutation(url, options)。在调用 send(payload) 时,会将 payload 作为 data (POST/PUT/PATCH) 或 params (GET/DELETE) 发送。
  2. 函数构建器: useMutation((...args) => RequestConfig, options)。业务入参自定义转换为请求配置,支持更复杂的请求构建逻辑。

适用场景

  • 统一前端项目中多个环境的请求配置。
  • 封装一套在 Web、小程序 (Taro/Uniapp) 之间通用且体验一致的数据获取层。
  • 配合 UI 组件库进行声明式的查询列表展示与表单提交操作。