Created
April 11, 2019 06:50
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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