The create 函数是 Zustand 中创建 React 绑定 store 的主要 API。它提供了一个基于 hook 的接口,用于在 React 组件中访问和更新状态。
有关框架无关的状态管理,请参阅 createStore。有关带有自定义相等性检查的 store,请参阅 createWithEqualityFn。
The create 函数接收一个状态创建函数作为输入,并返回一个自定义 React hook,该 hook 会
Sources: src/react.ts44-64 src/vanilla.ts9-14
The create 函数在 react.ts 中定义,并建立在 vanilla.ts 的核心 store 功能之上。
该实现利用了 React 与外部 store 的同步机制。
Sources: src/react.ts44-51 src/react.ts53-61
When using create, you provide a state creator function that defines
The state creator receives these parameters
| 参数 | 类型 | 描述 |
|---|---|---|
set | SetStateInternal<T> | Function to update state |
get | () => T | Function to get current state |
api | StoreApi<T> | Store API with methods like subscribe |
Sources: src/vanilla.ts28-37 src/vanilla.ts9-14
The returned hook can be used in multiple ways
Sources: src/react.ts38-42 tests/basic.test.tsx49-68 tests/basic.test.tsx70-90
Sources: tests/basic.test.tsx55-59
Sources: tests/basic.test.tsx76-81 tests/basic.test.tsx130-163
The create function works through these key steps
createStore from vanilla.ts to create the core storeuseStore (using React's useSyncExternalStore)Sources: src/react.ts53-61 src/vanilla.ts60-97
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
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