A small package that will helps you manage your app state using react context api using hooks
npm install react-context-simply --save
- state is an immutable object, can not be changed directly only by dispatching action
constanst.js
// file holds all our constants will be used in dispatching actions also in reducerexportconstINCREMENT='INCREMENT';exportconstDECREMENT='DECREMENT';actions.js
import{INCREMENT,DECREMENT}from"./constants";exportconstincrement=()=>({type: INCREMENT});exportconstdecrement=()=>({type: DECREMENT});reducers.js
import{INCREMENT,DECREMENT}from"./constants";exportdefaultfunctioncountReducer(state,action){switch(action.type){caseINCREMENT:
returnstate+1;caseDECREMENT:
returnstate-1;default:
returnstate;}}store.js
importcreateStateContextfrom'react-context-simply';importcountReducerfrom'./reducers';import*asactionsfrom'./actions'const{
useStateValue,
StateProvider,
StateContext
}=createStateContext({},countReducer,actions);constuseCountState=useStateValue;constCountState=StateProvider;constCountStateContext=StateContextexport{useCountState,CountState,CountStateContext};app.js
importReactfrom'react';import{CountState,useCountState}from'./store.js';functionCounter(){const[state,actions]=useCountState()const{increment, decrement}=actionsreturn(<Viewstyle={{flex: 1,flexDirection: 'column',alignItems: 'center',justifyContent: 'center'}}><TouchableOpacityonPress={()=>{increment()}}><Text>Increment</Text></TouchableOpacity><TouchableOpacityonPress={()=>{decrement()}}><Text>Decrement</Text></TouchableOpacity><Text>{state}</Text></View>);}exportdefaultclassAppextendsReact.Component{render(){return(<CountState><Counter/></CountState>);}}for me i prefer to seperate the code into files but you can do it in one file, its all up to you
the consumer component it should be a functional component but its possible to acces state in class based component like this:
importReact,{Component}from'react';import{CountStateContext}from'./store';classCounterextendsComponent{staticcontextType=CountStateContext;render(){const[state,actions]=this.context;}}Of course in real world app you will need to make async calls wether requesting an api or writing to storage whatever the reason why it will be one for sure, With React Context Simply it has a redux-thunk like already built-in
actions.js
exportconstcallApi=()=>(state,dispatch)=>{dispatch({type: CALL_API})try{// dispatching a loading actiondispatch(loading())constres=awaitfetch('http://jsonplaceholder.typicode.com/todos')consttodos=awaitres.json()// dispatching a sucess actiondispatch(succes(todos))}catch(error){// dispatching an error actiondispatch(fail(error))}}middlwares are known for extending with custom functionalities, basically its a function thats got passed a state and dispatch in arguments, in react context simply instead you return the next function will be called, it return the state along with the new dispatched action, also in sometime you want that middleware to be hooked only with one action or multiple actions or all actions, next section we will cover how you can do that by passing array of middlwares each contain the action will be associated with
exportconstlogger=([state,dispatch])=>{constnewDis=action=>{console.log('Dispatching Action => ',action)returndispatch(action)}return[state,newDis]}createStateContext(initialState,reducer,actions,[middlewares])createStateContext returns the provider as well as the hook that will be called inside the consumer to get the state and actions
- The
initialStateThe initial State to begin withone. - The
reducerA pure function that takes the previous state and an action, and returns the next state. based on the action passed to it - The
actionssets of actions that holds information that send data to your store - The
middlewaresare optioanl argument, is an array that hold objects, each contain the middlware and the action associated with it, for the action you can either pass the action constant or an array of actions, or an*which mean the middleware will be for all the actions
const{
useStateValue,
StateProvider,
StateContext
}=createStateContext([],todoReducer,actions,[{action: '*',middleware: logger},{action: [ADD_TODO],middleware: addTodo},{action: GET_TODOS,middleware: getTodos},]);A repo showing the usage of the package doing a Todo example and timer example
Rolling Your Own Redux with react hooks and context
Writing Redux-like simple middleware for React Hooks
State Management with React Hooks and Context API in 10 lines of code!