菜单

create

相关源文件

The create 函数是 Zustand 中创建 React 绑定 store 的主要 API。它提供了一个基于 hook 的接口,用于在 React 组件中访问和更新状态。

有关框架无关的状态管理,请参阅 createStore。有关带有自定义相等性检查的 store,请参阅 createWithEqualityFn

核心功能

The create 函数接收一个状态创建函数作为输入,并返回一个自定义 React hook,该 hook 会

  1. 管理跨组件渲染的状态持久化
  2. 提供用于高效访问状态切片的 selector
  3. 在选定的状态发生变化时自动触发重新渲染
  4. 暴露 store API 方法以进行直接操作

Sources: src/react.ts44-64 src/vanilla.ts9-14

API 定义

The create 函数在 react.ts 中定义,并建立在 vanilla.ts 的核心 store 功能之上。

该实现利用了 React 与外部 store 的同步机制。

Sources: src/react.ts44-51 src/react.ts53-61

State Creator Function

When using create, you provide a state creator function that defines

  1. The initial state values
  2. Actions that modify state
  3. Computed values derived from state

The state creator receives these parameters

参数类型描述
setSetStateInternal<T>Function to update state
get() => TFunction to get current state
apiStoreApi<T>Store API with methods like subscribe

Sources: src/vanilla.ts28-37 src/vanilla.ts9-14

使用模式

基本 Store 创建

Accessing State in Components

The returned hook can be used in multiple ways

Sources: src/react.ts38-42 tests/basic.test.tsx49-68 tests/basic.test.tsx70-90

Accessing Entire State

Sources: tests/basic.test.tsx55-59

Using Selectors for Performance

Sources: tests/basic.test.tsx76-81 tests/basic.test.tsx130-163

内部实现细节

The create function works through these key steps

  1. Calls createStore from vanilla.ts to create the core store
  2. Creates a bound React hook with useStore (using React's useSyncExternalStore)
  3. Merges the store API onto the hook function for direct access
  4. Returns the enhanced hook function

Sources: src/react.ts53-61 src/vanilla.ts60-97

Direct API Access

The returned hook exposes the store API as properties for direct access

Sources: src/react.ts58-59 tests/basic.test.tsx416-429 tests/basic.test.tsx431-452

TypeScript 集成

The create function has full TypeScript support for type-safe state management

Sources: tests/basic.test.tsx44-51

实现架构

The create function is part of a layered architecture where create builds on top of the core createStore function. The hook it returns leverages React's built-in useSyncExternalStore to handle subscriptions and re-renders efficiently.

Sources: src/react.ts53-64 src/react.ts16-37 src/vanilla.ts60-97

最佳实践

  1. Create stores outside components to ensure they're singletons
  2. Use selectors for performance to prevent unnecessary re-renders
  3. Keep stores modular by dividing complex state into logical domains
  4. Combine with middleware for features like persistence or immutable updates
  5. Use TypeScript interfaces for type safety and better IDE support

来源: tests/basic.test.tsx49-90 tests/basic.test.tsx130-163