Factory for reducer hooks with custom middleware with an identical API as React's useReducer
. Compatible with Redux middlware.
An example with redux-thunk
and redux-logger
.
import {createReducer} from 'react-use';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
const useThunkReducer = createReducer(thunk, logger);
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
const Demo = () => {
const addAndReset = React.useCallback(() => {
return dispatch => {
dispatch({ type: 'increment' });
setTimeout(() => {
dispatch({ type: 'reset', payload: 1 });
}, 1000);
};
}, []);
const [count, dispatch] = useThunkReducer(reducer, 1);
return (
<div>
<p>count: {count}</p>
<button onClick={() => dispatch(addAndReset())}>Add and reset</button>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
);
};
const useMiddlewareReducer = createReducer(...middlewares);