react-state-action-hooks
React hooks for managing state with (async) actions.
Installation
npm install react-state-action-hooks # for npm users yarn add react-state-action hooks # for yarn users
Basic Usage
Demo is available on CodeSandbox.
First import useActionState
react hook and ActionDefs
which is a type definition.
;
Define a state and action definition types (or interfaces).
State can be anything from number or string to nested object.
Actions
is an object each of whose keys is a (async) function that takes arbitrary number of parameters.
;
Then you can define the actual initial state and action definitions that comform to the types (interfaces) defined above.
Action definition (actionDefs
in the code below) is an object that has exactly the same keys action Actions
, but the corresponding value is a function that returns function.
The parameters of the outer function is the same as the ones defined in Actions
.
The parameters of the innner function is (state: State, actions: Actions)
and it should return (acynchronously)
a new state or nothing. You can also call as many other acitons as you want inside the action.
; ;
Then finally in a React stateless component, you can use state
and actions
by invoking useActionState
.
;
Advanced Usage
Using context
useActionState
can take the third parameter context
which should be a key-value object, to which
you can pass whatever values you want to have access to in an action.
The context then becomes available as the third parameter of the returned function in an action definition.
Here is an example:
; ;
Then the context becomes available in all the functions in action definition.
;
Contribution
Any kinds of contributions are welcome! Just submit issues or pull requests!
Author
Hitoshi Otsuki
License
MIT