Skip to content

Instantly share code, notes, and snippets.

@73nko
Created April 11, 2019 06:50
Show Gist options
  • Save 73nko/640a21d00e99411b0d97df04300acbac to your computer and use it in GitHub Desktop.
Save 73nko/640a21d00e99411b0d97df04300acbac to your computer and use it in GitHub Desktop.
A Hook to implement a logger in console after each reducer action is dispatched
function enchanceDispatchWithLogger(dispatch) {
return function (action) {
console.groupCollapsed('Action Type:', action.type);
return dispatch(action);
}
}
function useReducerWithLogger(...args) {
let prevState = useRef(initialState);
const [state, dispatch] = useReducer(...args);
const dispatchWithLogger = useMemo(() => {
return enchanceDispatchWithLogger(dispatch);
}, [dispatch]);
useEffect(() => {
if (state !== initialState) {
console.log('Prev state: ', prevState.current);
console.log('Next state: ', state);
console.groupEnd();
}
prevState.current = state;
}, [state]);
return [state, dispatchWithLogger];
}
function App() {
const [state, dispatch] = useReducerWithLogger(reducer, initialState);
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment