If you have come with Redux background and play around with React useReducer. You are properly missing some useful middleware like logger. This is especially significant when we try to debug in very complicated application. And I found this handy package:
Zaelot-Inc / use-reducer-logger
A very basic logger for the useReducer function in the React Hooks API.
use-reducer-logger
A very very basic logger for the useReducer
function in the React Hooks API. Inspired by redux-logger.
Usage
- Install with
npm install use-reducer-logger --save-dev
oryarn add use-reducer-logger -D
- Import logger with
import logger from 'use-reducer-logger';
- Wrap your reducer with logger before passing it to
useReducer
const [state, dispatch] = useReducer(logger(reducer), initialState);
See Example
In a Dev Environment
You should only use this in a dev
environment. So you could do something like this to apply the logger based on the env
.
function reducer(state, action) {
switch (action.type) {
case 'increment'
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
…This logger is easy to embed on reducer and super lightweight because it console.log without any extra dependency. It good enough to uncover the black box but there are few enhancements could be added on top of it:
- Fix the issue about useCallback in pure function
Failed to compile.
./src/Context.js
Line 28:29: React Hook "useCallback" is called in function "logger" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
This could be resolved by capitalise the first character of our logger function and declares as React function.
const Logger = (reducer) => {
// logger implementation
}
- Use Console.Group to divide every single action, previous state and next state in reducer and looks more nice and clean to me.
Thanks for reading :)
Top comments (0)