yc-sdk-hooks
v0.1.19
Published
React hooks for yc-sdk-ui
Maintainers
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-hooksPeer Dependencies
This package requires the following peer dependencies:
reactyc-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>) => voiduseAsyncState
异步状态管理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; // () => voidZustand 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 - 异步状态:
useXxxAsync或useXxx - Store:
useXxxStore
Store命名
- Store函数:
useXxxStore - Store数据Hook:
useXxx - Store加载Hook:
useXxxLoading - Store错误Hook:
useXxxError
最佳实践
- 统一状态结构: 所有状态都包含data、loading、error
- 标准方法: setData、setLoading、setError、reset、setPartialData
- 类型安全: 使用TypeScript严格类型定义
- 开发工具: 启用Zustand开发工具进行调试
- 错误处理: 统一的错误处理和回调机制
状态注册表
使用状态注册表管理所有状态:
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 buildDevelopment
npm run devLicense
MIT
