Last active
March 12, 2019 08:06
-
-
Save rudyhuynh/17e287a5b365ba94745b468f9bd8ab89 to your computer and use it in GitHub Desktop.
This file contains 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
import React from "react"; | |
/** | |
* Use just as the same as React.useReducer, but state and action are logged to the console. | |
* Example usage: | |
* ``` | |
* const [state, dispatch] = useDebugReducer('MyComponent', reducer, initialState) | |
* // Console: | |
* // MyComponent dispatch: {...} | |
* // \t MyComponent state: {...} | |
* ``` | |
* or | |
* ``` | |
* const [state, dispatch] = useDebugReducer(reducer, initialState) | |
* // log nothing | |
* ``` | |
* @param {string} name - A name to identify between each useDebugReducer call, can be ignored | |
*/ | |
export function useDebugReducer(name, ...params) { | |
if (typeof name === "function") { | |
return React.useReducer(name, ...params); | |
} else { | |
const [state, originDispatch] = React.useReducer(...params); | |
const dispatch = action => { | |
originDispatch(action); | |
console.log(name + " dispatched:", action); | |
}; | |
console.log(`\t ${name} state`, state); | |
return [state, dispatch]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment