Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

📡 A React useReducer() hook whose dispatcher supports thunks à la redux-thunk.

License

NotificationsYou must be signed in to change notification settings

nathanbuchar/react-hook-thunk-reducer

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 versionTravisDavid


Install

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);// ...}

Usage

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

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp