1 | import { useReducer, useRef, useCallback } from 'react';
|
2 | function isThunk(action) {
|
3 | return typeof action === 'function';
|
4 | }
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | export function useThunkReducer(reducer, initialState, initializer) {
|
10 | const [state, dispatch] = useReducer(reducer, initialState, initializer);
|
11 | const previousState = useRef();
|
12 | previousState.current = state;
|
13 | const thunkedDispatch = useCallback(function thunkedDispatch(action) {
|
14 | if (isThunk(action)) {
|
15 | return action(thunkedDispatch, () => previousState.current);
|
16 | }
|
17 | dispatch(action);
|
18 | },
|
19 |
|
20 |
|
21 | []);
|
22 | return [previousState.current, thunkedDispatch];
|
23 | }
|
24 |
|
\ | No newline at end of file |