https://github.com/sosukesuzuki/use-thunk-reducer
A Hook that enhanced useReducer with like redux-thunk.
https://github.com/sosukesuzuki/use-thunk-reducer
react reacthooks
Last synced: about 2 months ago
JSON representation
A Hook that enhanced useReducer with like redux-thunk.
- Host: GitHub
- URL: https://github.com/sosukesuzuki/use-thunk-reducer
- Owner: sosukesuzuki
- License: mit
- Created: 2019-02-26T15:18:17.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2019-02-26T15:18:39.000Z (almost 7 years ago)
- Last Synced: 2025-04-08T18:12:18.903Z (9 months ago)
- Topics: react, reacthooks
- Language: TypeScript
- Homepage:
- Size: 104 KB
- Stars: 5
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# useThunkReducer
A Hook that enhanced `useReducer` with like `redux-thunk`.
## Why?
React provides `useReducer`. It make we can use reducer to mange state in React. However, It isn't allow using middleware. So, we cannot use `redux-thunk` with useReducer. So, I implemented new `useReducer` that enhanced with like `redux-thunk`.
## Usage
Implement reducer as same as for normal `useReducer`.
```ts
type State = { count: number };
type Action = { type: "increase"; amount: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increase":
return { count: state.count + action.amount };
default:
throw new Error();
}
}
```
Declare async action like for `redux-thunk`.(But, second argument is not `getState`.)
```ts
const increaseAsync = (amount: number) => {
return (dispatch: React.Dispatch, state: State) => {
setTimeout(() => {
console.log(state);
dispatch({ type: "increase", amount });
}, 1000);
};
};
```
Implement Counter component.
```tsx
const initialState: State = { count: 0 };
function Counter() {
const [state, dispatch] = useThunkReducer(reducer, initialState);
const increaseTwoWithOneSecond = React.useCallback(
() => dispatch(increaseAsync(2)),
[]
);
return (
{state.count}
increase 2 with 1 second
);
}
```
## License
MIT