state-machine-component
state-machine-component copied to clipboard
update for Hooks? :)
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 :)
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))];
}