Awesome Open Source
Awesome Open Source
Sponsorship

🍸 flooks 3.0

A state manager for React Hooks, maybe the simplest.

npm GitHub Workflow Status Codecov npm bundle size npm type definitions GitHub

Auto loading state ▨ Modules ▨ Re-render control


English × 简体中文


Install

yarn add flooks

# or

npm install flooks

Example

// 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.

Demo

∷ Live demo ∷

API

useModel()

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 payload

now()

now 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
  },
});

Philosophy

  • 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.js or models.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.

License

MIT License (c) nanxiaobei


Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
javascript (66,517) 
react (4,905) 
redux (1,112) 
hooks (224) 
model (105) 
state (102) 
flux (95) 
store (63) 

Find Open Source By Browsing 7,000 Topics Across 59 Categories