Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update for Hooks? :) #4

Open
wizzard0 opened this issue Mar 5, 2019 · 1 comment
Open

update for Hooks? :) #4

wizzard0 opened this issue Mar 5, 2019 · 1 comment

Comments

@wizzard0
Copy link

wizzard0 commented Mar 5, 2019

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 :)

@developit
Copy link
Owner

developit commented Mar 19, 2019

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))];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants