Gaining Visibility Into Your State Changes In Redux

Two of the most important skills to have in a programming are to be able to get quick visibility into what is actually going on in your program at a given point in time, and second, to be able to quickly isolate any problems that you run into. The former of these actually greatly facilitates the latter.

While working on a strange and infuriating issue recently with a React Native/Redux application that I was working on, I found myself in a situation where I felt blind as to what was actually going on in my application (and why it was failing).

You see, mapStateToProps was never being called, yet my reducer was definitely being called and I was definitely returning a new state object from my reducer. I had confirmed this with console.logs. Additionally, I had already confirmed that mapStateToProps was definitely not being called at all (again, using console.logs).

After quintuple checking that everything was hooked up properly, and that my reducer was indeed returning new state (and not making the mistake of altering existing state in the reducer), I decided that whatever the error was, it was happening in between the time that the reducer returned the new state and the time that mapStateToProps was being called. In other words, it seemed like it wasn’t something in my code.

Since it is a rather rare occurrence that the bug is in the framework code and not my own code, I wanted some additional visibility into what was going on. I needed to first confirm that Redux knew the state had been updated and that it should therefore be calling mapStateToProps on all of my connected components.

It turns out, Redux has a perfect little tool for this. It is called state.subscribe().

You can add a few lines that look like this:

store = createStore( ... );
store.subscribe(() => {
  console.log("Store state changed");
  console.log(store.getState());
});

wherever you have defined your store (using createStore). Using this, you get some log output any time the store’s state is changed. Additionally, you can see exactly what the new state is.

I should also note that much of this visibility can also be achieved with the Redux DevTools extension (which also comes with quite a few nice additional features), but I wanted to be able to play with these events, and in so doing I gained more of an understanding of what is really going on under the hood in Redux.

Gaining Visibility Into Your State Changes In Redux

Leave a Reply

Your email address will not be published. Required fields are marked *