UNPKG

900 BJavaScriptView Raw
1import { useReducer, useRef, useCallback } from 'react';
2function isThunk(action) {
3 return typeof action === 'function';
4}
5/**
6 * Can be used the same way as useReducer, but allows functions to be passed as
7 * actions (aka thunks).
8 */
9export 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 // exhaustive-deps doesn't work with recursion
20 // eslint-disable-next-line react-hooks/exhaustive-deps
21 []);
22 return [previousState.current, thunkedDispatch];
23}
24//# sourceMappingURL=useThunkReducer.js.map
\No newline at end of file