DEV Community

Cover image for Add debug logger when useReducer in React

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 jefflombard / use-reducer-logger

A very basic logger for the useReducer function in the React Hooks API.


A very very basic logger for the useReducer function in the React Hooks API. Inspired by redux-logger.

screenshot of logger


  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';
  1. 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};
      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.

  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. Group-loggings

Thanks for reading :)

Discussion (0)