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 🙏

© 2025 – Pkg Stats / Ryan Hefner

yc-sdk-hooks

v0.1.19

Published

React hooks for yc-sdk-ui

Readme

yc-sdk-hooks

React hooks for yc-sdk-ui package collection.

Installation

npm install yc-sdk-hooks
# or
yarn add yc-sdk-hooks
# or
pnpm add yc-sdk-hooks

Peer Dependencies

This package requires the following peer dependencies:

  • react
  • yc-sdk-ui

标准状态管理架构

这个包提供了一套标准化的状态管理工具,遵循以下架构原则:

状态类型分类

  • UI状态: 使用 useState + useStandardState - 弹窗、表单、界面交互
  • 服务端数据: 使用 useAsyncState - API调用、数据请求
  • 全局共享状态: 使用 createStandardStore + Zustand - 跨组件数据共享
  • URL参数: 使用 React Router - 路由状态管理

核心 Hooks

useStandardState

标准UI状态管理Hook,包含data、loading、error三个核心状态。

import { useStandardState } from 'yc-sdk-hooks';

interface FormState {
  name: string;
  email: string;
  age: number;
}

const formState = useStandardState<FormState>({
  name: '',
  email: '',
  age: 0,
});

formState.data;      // FormState | null
formState.loading;   // boolean
formState.error;     // Error | null
formState.setData;   // (data: FormState) => void
formState.setLoading; // (loading: boolean) => void
formState.setError;   // (error: Error | null) => void
formState.reset;      // () => void
formState.setPartialData; // (data: Partial<FormState>) => void

useAsyncState

异步状态管理Hook,适用于API调用。

import { useAsyncState } from 'yc-sdk-hooks';

const fetchUser = async (userId: string) => {
  const response = await fetch(`/api/users/${userId}`);
  return response.json();
};

const userState = useAsyncState(
  (userId: string) => fetchUser(userId),
  {
    resetOnCall: true,
    onSuccess: (data) => console.log('加载成功:', data),
    onError: (error) => console.error('加载失败:', error),
  }
);

userState.data;     // User | null
userState.loading;  // boolean
userState.error;    // Error | null
userState.execute;  // (userId: string) => Promise<User>
userState.reset;    // () => void

Zustand Store 工厂

createStandardStore

创建标准化的Zustand Store。

import { createStandardStore, createStandardStoreHooks } from 'yc-sdk-hooks';

interface UserProfile {
  id: string;
  name: string;
  email: string;
}

const useUserProfileStore = createStandardStore<UserProfile>({
  name: 'userProfile',
  initialData: null,
  enableDevtools: true,
  customActions: (set, get) => ({
    updateProfile: (updates: Partial<UserProfile>) => {
      const currentData = get().data;
      if (currentData) {
        set((state) => ({
          data: { ...currentData, ...updates },
          lastUpdated: Date.now(),
        }));
      }
    },
  }),
});

const userProfileHooks = createStandardStoreHooks(useUserProfileStore);

export const {
  useStore: useUserProfileStoreRaw,
  useData: useUserProfile,
  useLoading: useUserProfileLoading,
  useError: useUserProfileError,
  useLastUpdated: useUserProfileLastUpdated,
} = userProfileHooks;

Web3 Hooks

useWeb3Clients

A hook that provides Web3 client instances for blockchain interactions.

Features

  • Automatic chain detection and configuration
  • Public client for read operations
  • Wallet client for write operations
  • Support for multiple chains (Ethereum, Polygon, Arbitrum, Sepolia)

Usage

import { useWeb3Clients } from 'yc-sdk-hooks';

function MyComponent() {
  const {
    publicClient,
    walletClient,
    getWalletClient,
    chain,
    chainId,
    address,
    isConnected
  } = useWeb3Clients();

  // Read from blockchain
  const balance = await publicClient.getBalance({
    address: '0x...'
  });

  // Write to blockchain
  if (isConnected) {
    const wallet = getWalletClient();
    const hash = await wallet.writeContract({
      address: '0x...',
      abi: [...],
      functionName: 'transfer',
      args: [...]
    });
  }

  return (
    <div>
      {isConnected ? (
        <p>Connected: {address}</p>
      ) : (
        <p>Not connected</p>
      )}
    </div>
  );
}

Supported Chains

  • Ethereum Mainnet (1)
  • Polygon (137)
  • Arbitrum (42161)
  • Sepolia Testnet (11155111)

内置示例

1. 用户个人资料 Store

import { useUserProfile, useUserProfileLoading } from 'yc-sdk-hooks';

function ProfileComponent() {
  const profile = useUserProfile();
  const loading = useUserProfileLoading();

  if (loading) return <div>加载中...</div>;

  return (
    <div>
      <h1>{profile?.name}</h1>
      <p>{profile?.email}</p>
    </div>
  );
}

2. 弹窗状态管理

import { useModalState } from 'yc-sdk-hooks';

function ModalExample() {
  const modal = useModalState({
    title: '确认删除',
    size: 'md',
  });

  return (
    <div>
      <button onClick={() => modal.open()}>
        打开弹窗
      </button>

      {modal.isOpen && (
        <Modal onClose={modal.close}>
          <h2>{modal.title}</h2>
          <button onClick={modal.close}>关闭</button>
        </Modal>
      )}
    </div>
  );
}

3. API状态管理

import { useUserApi } from 'yc-sdk-hooks';

function UserComponent({ userId }: { userId: string }) {
  const { useUser } = useUserApi();
  const userState = useUser(userId);

  return (
    <div>
      {userState.loading && <div>加载中...</div>}
      {userState.error && <div>错误: {userState.error.message}</div>}
      {userState.data && (
        <div>
          <h3>{userState.data.name}</h3>
          <p>{userState.data.email}</p>
        </div>
      )}
    </div>
  );
}

命名规范

Hook命名

  • UI状态: useXxxState
  • 异步状态: useXxxAsyncuseXxx
  • Store: useXxxStore

Store命名

  • Store函数: useXxxStore
  • Store数据Hook: useXxx
  • Store加载Hook: useXxxLoading
  • Store错误Hook: useXxxError

最佳实践

  1. 统一状态结构: 所有状态都包含data、loading、error
  2. 标准方法: setData、setLoading、setError、reset、setPartialData
  3. 类型安全: 使用TypeScript严格类型定义
  4. 开发工具: 启用Zustand开发工具进行调试
  5. 错误处理: 统一的错误处理和回调机制

状态注册表

使用状态注册表管理所有状态:

import { stateRegistry } from 'yc-sdk-hooks';

stateRegistry.register({
  type: 'global',
  name: 'userProfile',
  defaultState: null,
});

const allStates = stateRegistry.list();
const globalStates = stateRegistry.listByType('global');

Building

npm run build

Development

npm run dev

License

MIT