You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi, I wanted to share a simple hook I've built on top of use-immer that I've found very useful, and ask if there's any interest in including it in the library. I call it useStateMachine, and (adapting the example from your README), one uses it like this:
The API bears an obvious resemblance to that of useImmerReducer/useReducer, but with some important differences:
instead of switching on an action type, one simply writes "methods" which mutate the state (or return a fresh one)
instead of getting back a single dispatch function, one gets back an object of callbacks corresponding to the methods
I find this pattern much nicer to use than standard reducers for a few reasons:
writing methods is nicer than putting everything into a big switch statement and having to break/return from each case
the returned callbacks can be passed directly as props to children (rather than wrapping with arg => dispatch({ type: 'foo', arg }) -- blech!), and they are properly memoized!
in TypeScript, one doesn't need to make an Action union type and keep it up to date; everything is inferred from the method types
Hi, I wanted to share a simple hook I've built on top of
use-immer
that I've found very useful, and ask if there's any interest in including it in the library. I call ituseStateMachine
, and (adapting the example from your README), one uses it like this:The API bears an obvious resemblance to that of
useImmerReducer
/useReducer
, but with some important differences:dispatch
function, one gets back an object of callbacks corresponding to the methodsI find this pattern much nicer to use than standard reducers for a few reasons:
break
/return
from each casearg => dispatch({ type: 'foo', arg })
-- blech!), and they are properly memoized!Action
union type and keep it up to date; everything is inferred from the method typesThe hook is very simple; here's the code for it:
If you think this would make a good addition to the library I'd be happy to open a PR.
The text was updated successfully, but these errors were encountered: