DEV Community

Cover image for Add debug logger when useReducer in React
Devdy
Devdy

Posted on

Add debug logger when useReducer in React

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:

GitHub logo 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.

screenshot of logger

Usage

  1. Install with npm install use-reducer-logger --save-dev or yarn add use-reducer-logger -D
  2. Import logger with
import logger from 'use-reducer-logger';
Enter fullscreen mode Exit fullscreen mode
  1. Wrap your reducer with logger before passing it to useReducer
const [state, dispatch] = useReducer(logger(reducer), initialState);
Enter fullscreen mode Exit fullscreen mode

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();
  }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

This could be resolved by capitalise the first character of our logger function and declares as React function.

const Logger = (reducer) => {
  // logger implementation
}
Enter fullscreen mode Exit fullscreen mode
  • Use Console.Group to divide every single action, previous state and next state in reducer and looks more nice and clean to me. Group-loggings

Thanks for reading :)

Top comments (0)