简体中文 | English
Global state management based on React Hooks
- One API, Simple but efficient
- Strongly typed with Typescript
- React hooks style
- Minimum granularity update component
It can be used as
useState
in the global context. Indeed affect the whole body!
$ yarn add nostore
# or
$ npm install nostore --save
// store.js
import { createStore } from "nostore";
const useStore = createStore({ count: 1 });
export default useStore;
// action
export function useDecrease() {
const [, setStore] = useStore();
return () => {
setStore(prevStore => ({
count: prevStore.count - 1
}));
};
}
// multiple actions
export function useAction() {
const [store, setStore] = useStore();
return {
decrease() {
setStore({
count: store.count - 1
});
},
// async action
async increase() {
await wait(2000);
setStore(prevStore => ({
count: prevStore.count + 1
}));
}
};
}
// Increase.jsx
import useStore, { useAction } from "./store.js";
function Increase() {
const [store] = useStore();
const { increase } = useAction();
return (
<>
<h1>{store.count}</h1>
<button onClick={increase}>increase</button>
</>
);
}
// Decrease.jsx
import useStore, { useDecrease } from "./store.js";
function Decrease() {
const [store] = useStore();
const decrease = useDecrease();
return (
<>
<h1>{store.count}</h1>
<button onClick={decrease} />
</>
);
}