🍸 flooks 3.0
A state manager for React Hooks, maybe the simplest.
Auto loading state ▨ Modules ▨ Re-render control
English | 简体中文
Install
yarn add flooks
# or
npm install flooks
Example
// counter.js
const counter = (now) => ({
count: 0,
add() {
const { count } = now(); // <---- get own model
now({ count: count + 1 }); // <-- set own model
},
});
export default counter;
// trigger.js
import counter from './counter';
const trigger = (now) => ({
async addLater() {
const { add } = now(counter); // <-- get other models
await new Promise((resolve) => setTimeout(resolve, 1000));
add();
},
});
export default trigger;
// Demo.jsx
import useModel from 'flooks';
import counter from './counter';
import trigger from './trigger';
function Demo() {
const { count, add } = useModel(counter, ['count']); // <-- `deps` 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.
Demo
API
useModel(model, deps)
const { a, b } = useModel((now) => data, ['a', 'b']);
A React Hook, pass a model function, returns the model data.
* Re-render control: deps
is optional, the same as that of React.useEffect
:
- If pass nothing, all updates in the model will trigger a re-render
- If pass an empty array (
[]
), it will never trigger a re-render - If pass a dependency list (
['a', 'b']
), it will trigger a re-render only when any dependency changes
now()
import anotherModel from './anotherModel';
const ownModel = (now) => ({
fn() {
const { a, b } = now(); // get own model
const { x, y } = now(anotherModel); // get other models
now(payload); // set own model
},
});
now()
to get own modelnow(anotherModel)
to get other modelsnow(payload)
to update own model,payload
is an object
Philosophy
- The philosophy of flooks is decentralization, so recommend binding one component and one model as one.
- No need to add a file like
store.js
ormodels.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.