- Notifications
You must be signed in to change notification settings - Fork12
📡 A React useReducer() hook whose dispatcher supports thunks à la redux-thunk.
License
nathanbuchar/react-hook-thunk-reducer
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Akin toredux-thunk,
useThunkReducer()augments React'suseReducer()hook so that the action dispatcher supportsthunks. Now, you can write action creators that return a function rather than an action!Requires React v16.8 and above.
npm install react-hook-thunk-reducer
Then just import it and use it like you wouldReact.useReducer().
import{useThunkReducer}from'react-hook-thunk-reducer';functionComponent({ initialState}){const[state,dispatch]=useThunkReducer(reducer,initialState);// ...}
Create your actions just like you would in Redux. Similar toredux-thunk, if an action returns a function, it's treated as athunk and has access to the current state.
functionincrement(){return{type:'increment'};}functionincrementIfOdd(){return(dispatch,getState)=>{const{ count}=getState();if(count%2!==0){dispatch(increment());}};}
Create your functional component and call theuseThunkReducer() hook as if it wereReact.useReducer();
import{useThunkReducer}from'react-hook-thunk-reducer';// ...functionreducer(state,action){switch(action.type){case'increment':return{count:state.count+1};default:thrownewError();}}functionCounter({ initialState}){const[state,dispatch]=useThunkReducer(reducer,initialState);// ...return(<> Count:{state.count}<buttononClick={onButtonPress}>+</button></>);}
Dispatch your actions using the augmenteddispatch function.
constonButtonPress=()=>{dispatch(incrementIfOdd());};
The value of the inner function will be returned when dispatching thunks.
functionincrementAndReturnCount(){return(dispatch,getState)=>{dispatch(increment());returngetState().count;};}constnewCount=dispatch(incrementAndReturnCount());
About
📡 A React useReducer() hook whose dispatcher supports thunks à la redux-thunk.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.