DEV Community

artydev
artydev

Posted on • Updated on

Meiosis a simple state management for React

I have posts a few articles on Meiosis, please read them if you are new to this pattern

Here is a use case for React.

You can test it here MeioisisReact

/*global React, ReactDOM, flyd, mergerino*/
const merge = mergerino;

var Actions = (update) => {
  return {
    incr : () => update({
      counter: (c) => c + 1
    })
}}

var initialState = {
  counter : 0
}

var update = flyd.stream();
var states = flyd.scan(merge, initialState, update);
var actions = Actions(update);

var App = function ({ states, actions }) {
  var [init, setInit] = React.useState(false);
  var [state, setState] = React.useState(states());

  // avoid infinit loop
  if (!init) {
    console.log("start")
    setInit(true);
    states.map((s) => setState(s));
  }
  return (
    <div>
      <h1>{state.counter}</h1>
      <button onClick = {actions.incr}>INC</button>
    </div>
  );
};

ReactDOM.render(  
  <App states={states} actions={actions} />,
  document.getElementById("app")
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)