Viewing your state with React’s useReducer

In a previous post I shared an approach to enhance reducer actions in your React Context. I’ve worked through this a few times and found one thing this approach doesn’t have that something like Redux does: the logger. Well, there’s a separate library for logging called redux-logger. This nifty little piece of middleware writes out all of the dispatches and state changes to the console. This is exceptionally helpful to quickly debug your state and see how your state is responding.

Can we do this with our useReducer approach? Sure thing! I’ve seen other posts about adding a middleware into useReducer and that seemed overly complicated, let’s see a simpler approach.

Add logging to view your state

To resolve this little issue, I added some logging to my reducer and provider component. I recommend reviewing my previous post, Enhancing reducer actions in React Context, to get context into the following code snippets.

Logging in the context provider

In my ApiContext, which manages my state, I added:

  React.useEffect(() => {
    console.log('pinned state', state);
  }, [state]);

Anytime the state changes, it will log the state to the console.

Logging in the reducer

In my reducer, in the reducer function I also added a log:

export function reducer(state = initialState, action) {
  console.log('pinned dispatched', action);
  switch (action.type) {

Anytime a dispatch is run, it will log the data being sent in (in action). Then, since we have the above log in the ApiContext, when the reducer changes the state, the state is then logged.

That’s it!

Not too bad, right? I can now view what is being sent to my reducer and what the resulting state now is. ❤️ This is a pretty lightweight approach and tremendously helpful. This is much lighter on your application than bringing in a full library and adding in some middleware in your reducer.

Wait, what about logging in production?

As I understand the console.log, it only runs when the dev toolbar is open, so running this in prod should have no impact. However, my memory isn’t always reliable and I can’t find evidence of this online, do you know or have something official saying so? If so, please leave a comment below and I’ll update accordingly.

Alternatively, you can include in the above code spots a basic condition like if (process.env.REACT_APP_ENV === 'dev') console.log(...). Of course, you’d have to set up the proper variables in your project, but I’d suspect you already have those.


Interested in receiving content like this right in your inbox, subscribe below!

Join 1,324 other subscribers

One thought on “Viewing your state with React’s useReducer

Add yours

Leave a Reply

Powered by WordPress.com.

Up ↑

%d bloggers like this: