js:react使用zustand实现状态管理
文档
- https://www.npmjs.com/package/zustand
- https://github.com/pmndrs/zustand
- https://docs.pmnd.rs/zustand/getting-started/introduction
安装
npm install zustand
示例
定义store
store/index.js
import { create } from "zustand";
export const useCountStore = create((set) => ({
// state
count: 0,
// action
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
使用store
app.jsx
import React, { useState, useEffect } from "react";
import { useCountStore } from "./store/index.js";
function FooCounter() {
const count = useCountStore((state) => state.count);
return <h1>count: {count}</h1>;
}
function BarCounter() {
const increment = useCountStore((state) => state.increment);
const decrement = useCountStore((state) => state.decrement);
return (
<>
<button onClick={increment}>increment</button>
<button onClick={decrement}>decrement</button>
</>
);
}
export default function App() {
return (
<>
<FooCounter />
<BarCounter />
</>
);
}