必须完成zustand安装、store创建与组件消费三步闭环:先确认react依赖存在,再运行npm install zustand,接着在src/store/下创建usecounterstore.ts,最后在app.tsx中导入并解构使用。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

在 Cursor 编辑器中新建 React 项目后,要让全局状态管理生效,必须完成 Zustand 的安装、Store 创建与组件消费三步闭环,缺一不可。
确认项目已初始化为 React(TS 或 JS)
Cursor 新建项目时默认使用 Vite 模板,需先检查 【package.json 中 presence of "react" and "react-dom"】。若缺失,执行 npm create vite@latest . --template react-ts 覆盖重置——这一步不可跳过,否则后续 import 会报错 Module not found。
打开终端面板(Ctrl+`),确保当前路径是项目根目录,再继续下一步。
安装 Zustand 依赖
在 Cursor 内置终端中运行:
npm install zustand
或使用 yarn:
yarn add zustand
安装完成后,node_modules 中会出现 zustand 文件夹,且 package.json 的 dependencies 字段新增 "zustand": "^4.5.0"(版本号以实际为准)。
创建第一个 Zustand Store
在 src/store/ 下新建 useCounterStore.ts(JS 项目用 .js):
输入以下内容并保存:
import { create } from 'zustand';
export const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 }))
}));
注意:文件名必须以 use 开头,这是 Cursor 自动识别 React Hook 的前提;【create 函数参数必须返回对象,不能是 undefined 或 Promise】,否则调用时会触发 TypeError。
在组件中消费 Store
打开 src/App.tsx,替换默认内容:
第一步:导入 Store
import { useCounterStore } from './store/useCounterStore';
第二步:解构使用
function App() {
const { count, increment, decrement } = useCounterStore();
return (
<div>
<p><code> <h1>Count: {count}</h1>
<button onclick="{increment}">+</button>
<button onclick="{decrement}">-</button>











