use-simple-state
A simple, lightweight (1kb), dependency-free state manager for React, built using hooks.
Note: lists react@16.7.0-alpha.2 as a peer dependency. Once 16.7 ships this will be updated to use ^react@16.7.0
Installation
Intall the package using yarn or npm:
yarn add use-simple-state
npm install use-simple-state --save
Ensure you have the correct version of react
installed, as well the corresponding react-dom
version (this step will be removed in a future release):
yarn add react@16.7.0-alpha.2 react-dom@16.7.0-alpha.2
npm install react@16.7.0-alpha.2 react-dom@16.7.0-alpha.2 --save
Getting Started
Before we get started, we first need an initial state, as well as some actions and at least one reducer:
Lastly, we simply import SimpleStateProvider
, pass our reducers and initial state, then wrap our app's root component:
And that's it.
Now whenever we want to access or update our state, we just import the useSimple
hook:
Async Actions
Comes with built-in support for asynchronous actions by providing an API similar to redux-thunk
.
If a function is passed to dispatch
it will be called with dispatch
and state
as parameters. This allows us to handle async tasks, like the following example of an action used to authenticate a user:
Note: dispatch
will return the result of any async actions, opening up possibilities like chaining promises from dispatch
:
API
useSimple
A custom React hook that lets us access our state and dispatch
function from inside components.
Usage:
Returns an array containing a state
object and a dispatch
function.
useSimple
has two optional parameters: mapState
and mapDispatch
:
mapState
If mapState
is passed, it will be used to compute the output state and the result will be passed to the first element of the array returned by useSimple
.
Usage
Note: null
can also be passed if you want to use mapDispatch
but have no use for a mapState
function.
mapDispatch
mapDispatch
can be used to pre-wrap actions in dispatch
. If mapDispatch
is passed, the result will be given as the second element of the array returned by useSimple
.
Usage
SimpleStateProvider
A React component that wraps an app's root component and makes state available to our React app.
Usage
Has two mandatory props: initialState
and reducers
, as well as an optional prop: middleware
initialState
An object representing the initial state of our app.
reducers
An array of reducers.
Reducers take an action as well as the current state and use these to derive a new state. If a reducer returns undefined
there will be no state update.
Reducers should have the following API:
middleware
An array of middleware functions.
Middleware functions are used to handle side effects in our app.
A middleware function is given two parameters: state
and action
.
If any middleware returns null
, the triggering action
will be blocked from reaching our reducers
and the state will not be updated.