Skip to content

Instantly share code, notes, and snippets.

@rudyhuynh
Last active March 12, 2019 08:06
Show Gist options
  • Save rudyhuynh/17e287a5b365ba94745b468f9bd8ab89 to your computer and use it in GitHub Desktop.
Save rudyhuynh/17e287a5b365ba94745b468f9bd8ab89 to your computer and use it in GitHub Desktop.
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