一、Recoil
首先安装依赖:
npm install recoil
示例代码:
javascript
// src/store/index.js
import { countState } from './counterState';
export {
countState
};
javascript
// src/store/counterState.js
import { atom } from 'recoil';
export const countState = atom({
key: 'countState',
default: 0,
});
javascript
// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import { RecoilRoot } from 'recoil';
createRoot(document.getElementById('root')).render(
<StrictMode>
<RecoilRoot>
<App />
</RecoilRoot>
</StrictMode>,
)
javascript
// src/App.jsx
import React from 'react';
import { useRecoilState } from 'recoil';
import { countState } from './store';
const App = () => {
const [count, setCount] = useRecoilState(countState);
return (
<div>
<h1>Counter</h1>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default App;
二、Zustand
首先安装依赖:
javascript
npm install zustand
示例代码:
javascript
// src/store/index.js
import useCounterStore from "./counterStore";
export { useCounterStore };
javascript
// src/store/counterStore.js
import { create } from 'zustand';
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 }))
}));
export default useCounterStore;
javascript
// src/App.jsx
import React from 'react';
import { useCounterStore } from './store';
const App = () => {
const counterStore = useCounterStore();
console.log(counterStore);
return (
<div>
<p>Count: {counterStore.count}</p>
<button onClick={() => counterStore.increment()}>Increment</button>
</div>
);
};
export default App;