state-machine-component icon indicating copy to clipboard operation
state-machine-component copied to clipboard

update for Hooks? :)

Open wizzard0 opened this issue 6 years ago • 1 comments

now that Preact X is out (and after sorting out urgent issues of course), it makes total sense to make a functional counterpart of this library :)

wizzard0 avatar Mar 05 '19 22:03 wizzard0

Here's what I think the API could look like:

function reduce(state, action) {
  switch (action.type) {
    case '@@INIT': return { count: 0 }
    case 'ADD': return { count: state.count+1 }
  }
}

function App(props) {
  const [state, action] = useStateMachine(reduce)
  return (
    <div class="counter">
      Current count: {state.count}
      <button onClick={action('ADD')}>Add 1</button>
    </div>
  )
}

render(<App />, document.body)

Interestingly, this is only one tiny step from the standard useReducer hook. So much so, that the entire implementation would be this:

import { useReducer, useState } from 'preact/hooks';

export default function useStateMachine(reducer) {
  const [state, dispatch] = useReducer();
  const [cache] = useState({});
  return [state, type => cache[type] || (cache[type] = (...args) => dispatch(type, ...args))];
}

developit avatar Mar 19 '19 01:03 developit