A state manager for React Hooks, maybe the simplest.
Auto loading state ▨ Modules ▨ Re-render control
English × 简体中文
yarn add flooks
# or
npm install flooks// counter model
const counter = (now) => ({
count: 0,
add() {
const { count } = now(); // <----- now() :: get own model
now({ count: count + 1 }); // <--- now(payload) :: set own model
},
});
export default counter;// trigger model
import counter from './counter';
const trigger = (now) => ({
async addLater() {
const { add } = now(counter); // <-- now(model) :: get other models
await new Promise((resolve) => setTimeout(resolve, 1000));
add();
},
});
export default trigger;// App component
import useModel from 'flooks';
import counter from './counter';
import trigger from './trigger';
function App() {
const { count, add } = useModel(counter, ['count']); // <-- ['count'] :: re-render control
const { addLater } = useModel(trigger); // <-------- addLater.loading :: auto loading state
return (
<>
<p>{count}</p>
<button onClick={add}>+</button>
<button onClick={addLater}>+ ⌛{addLater.loading && '...'}</button>
</>
);
}* Auto loading state - When someFn is async, someFn.loading can be used as its loading state.
Pass a model, returns the model data.
* Re-render control - useModel(model, deps), deps is optional, same as that of useEffect.
const { a, b } = useModel(someModel, ['a', 'b']);
// useModel(model) <-------------- now(payload) always trigger a re-render
// useModel(model, []) <---------- now(payload) never trigger a re-render
// useModel(model, ['a', 'b']) <-- now(payload) trigger a re-render when a or b inside payloadnow is the param to model, can be used in 3 ways.
import anotherModel from './anotherModel';
const ownModel = (now) => ({
modelFn() {
const { a, b } = now(); // <-------------- 1. get own model
now({ a: a + b }); // <------------------- 2. update own model (payload is an object)
const { x, y } = now(anotherModel); // <-- 3. get other models
},
});- The philosophy of flooks is decentralization, so recommend binding a page component and a model as one.
- No need to add a file like
store.jsormodels.js, because no need to distribute the store from top now. - A model has its own space, when call
now(anotherModel)to get other models, all models can be connected.