Fixing the past is hard, how ReduxDevTools and Reselect can help
Tags: react, redux, reselect, reduxdevtools
Published: 2019-04-29 00:46:04

---
title: Fixing the past is hard, how ReduxDevTools and Reselect can help
published: true
description: Traversing, understanding, and fixing state issues from Redux by using Redux DevTools; Making state more simplistic w/ Reselect  
tags: React, Redux, Reselect, ReduxDevTools,
---
<img width="60%" alt = "back to the future mini gif" src ="https://media.giphy.com/media/l0NwQEjAS77JyRvig/source.gif"/>

<h1>"Staying stuck in the past is unhealthy"</h1> 
<p>
   Who ever said that staying stuck in the past is unhealthy for you was absolutely right, but sometimes there's things we can learn from the past to improve our future <strong>actions</strong> (pun intended). If you're familiar with the Redux library and its' methodology then you've probably heard of a term called "time-traveling", but could be unsure of what it means and how it can benefit yourself, your application structure and relation to Redux, along with your overall sanity when it comes to debugging state issues in a Redux store. Let's have a closer look at the tools that exist today, before we <strong>visit the past</strong> (pun intended - again)   
</p>
<hr/>
<h1>Available Arsenal.</h1>
<p>
 <ol>
  <li><a href = "https://github.com/LogRocket/redux-logger">Redux-Logger</a>: Is a middleware available for use with the Redux library that allows actions dispatched to be logged to your favorite browser's console. In addition to printing the actions dispatched, the previous and upcoming states are included. This allows you to see the result of the action dispatched in real time, but does not allow you to manually go back in time and <strong>replay</strong> such an action to further understand its' effects on your store.</li>
  <li><a href = "https://github.com/zalmoxisus/redux-devtools-extension">Redux-DevTools</a>: Is a middleware available for use with the Redux library similar to Redux-Logger, but instead provides a intuitive GUI to use that's integrated to your favorite browser. Like Redux-Logger, the actions dispatched to the store are recorded and displayed, but a major benefit is the ability to rewind, skip/fast-forward, stop, pause, and play actions that have occurred in your application. In addition, extra configs can be added to really assist in your debugging efforts such as the <strong><a href = "https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/Features/Trace.md">trace option</a></strong> that will allow you to see where in your app the action was dispatched from.</li>
</ol>
<ol>I'm sure there's more available logging tools for Redux out there, but these are the two I'm most versed in/seen the most in enterprise applications</ol>
</p> 
<hr/>
<h1>Knowing your available tools is most of the battle</h1>
<img alt = "flux capacitor getting ready" width = "60%" src = "https://media.giphy.com/media/149gVqjyvMnV72/giphy.gif"/> 
<p>
    So now that we know which tools are available, and their usages regarding Redux logging/debugging, lets dive into one of the topics of discussion; Redux DevTools.<br/>
 To make this an interactive learning experience I've decided to <a href = "https://github.com/flexdinesh/react-redux-boilerplate">clone a simple boilerplate that came with React, Redux, ReduxDevTools, and Reselect (more on this later) installed.</a> The repo has a good readme which includes how to get everything up and running, so in an effort to keep this tutorial short, I won't be covering this. Once installed and setup we need to add the Redux-DevTools extension to our favorite browser. You can find instructions on how to do that <a href = "https://github.com/zalmoxisus/redux-devtools-extension#installation">HERE</a>. If you're using the Chrome or Firefox browsers it's a simple plugin install to get it going, if not, follow the instructions in the previous link to get Redux-DevTools setup. Once installed, go back to your cloned application running <strong>(if it's not running start it up)</strong> and refresh the page. You should see the Redux-DevTools icon glowing......<b>EXCITING!</b> 
</p>
<hr/>
<h1>Is the Flux Capacitor ready yet?</h1>
<p>
  <strong>Patience Marty!</strong> Before we get into all the cool time traveling aspects of the extension, lets get a feel for some basics of our new extension. Clicking on the extension's icon for the first time will reveal the the actions that was dispatched to the store and the delta (change) that occurred as a result. If there was a change to the state, you would see it here, but since we just got on the page it will say "states are equal" as seen below. 
<img src = "https://thepracticaldev.s3.amazonaws.com/i/icgujgkcjnkckovuy7bu.JPG" alt = "states are equal in Redux-DevTools Extension" /> 
<figcaption>Redux-DevTools GUI</figcaption> 
<hr/>
You should notice on the top row of the extension an option to switch the view from <strong>"diff"</strong> to <strong>"action"</strong>. If you were to switch the view you can now see the action itself which includes the type and payload (if applicable) as seen below. 
<img src = "https://thepracticaldev.s3.amazonaws.com/i/zhbes0l40akx0ri9q32r.JPG" alt = "action view in Redux-DevTools" /> <br/>
<figcaption>Redux-DevTools action view</figcaption> 
<hr/>
The last option that we're covering in this tutorial arguably the most important, the <strong>"state"</strong> view. Clicking on this view will reveal what the store looks like after being reduced from a dispatched action. As seen below, we now have a bird eye view of how our store looks....<strong>NEAT!</strong>
<img src = "https://thepracticaldev.s3.amazonaws.com/i/abmyb05uct6uj97vimz7.JPG" alt = "state view in Redux-DevTools" /> <br/>
<figcaption>Redux-DevTools state view</figcaption> 
</p> 
<hr/>
<h1>Can we go save the dinosaurs yet?</h1> 
<img width = "60%" alt = "Legend of Zelda - Dont go alone gif" src = "https://media.giphy.com/media/ElSNi8FdSB7RS/giphy.gif" />


Almost Marty, but I have another feature of our new extension to show you that will assist you from going this journey alone (an old man told me that in 86'). If you're anything like me, looking at JSON or raw objects all day can become dizzying. You may of noticed a sub-option in our new extension called <strong>"chart"</strong>. Clicking on the actions options and the chart sub-option will reveal a nicely drawn graph of the action dispatched and it's relationship to the store's state. This is cool, but where it really shines is drawing the relationship between the action dispatched and the future state. <br/>
<hr/>
Go ahead and click on the state option and chart sub-option. You should notice the graph drawn includes the different properties available on the store, and how they interconnect. If you were to hover over the individual nodes on the chart, it will allow you to peek at the current state of that particular property in the store. <img src = "https://thepracticaldev.s3.amazonaws.com/i/sffpws9kxs6tzmjqyz97.JPG" alt = "state view CHART in Redux-DevTools" />
<figcaption>peek-a-boo, state I see you</figcaption>

<h1>If my calculations are correct, when this baby hits 88 miles per hour, you gonna see some serious s**t.</h1>  
<img width = "60%" alt = "back to the future 88mph" src = "https://media.giphy.com/media/xsF1FSDbjguis/giphy.gif" />
<p>
  Alright Marty, now that you have a quick overview of our tools, you're ready to go to the past to understand how our future is going to look. <br/>

Go to the GitHub input box on our application and begin to type in your or your favorite GitHub user's name and hit enter; You should see a list of repos applicable to that name render on the page. Yay, our application is working as expected, but what actions happened, and in what order, and how did this effect the store's state? Open the Redux-DevTools extension, select the <strong>"diff"</strong> option and <strong>"state"</strong> sub-option. Once done, hover over the first action in the list and click the word <strong>"jump"</strong>. You should of noticed the rendered repo list was taken away, your state diff looks different, and the slider near the play button has moved towards the left as well! Marty....we're now in the past! From here you can now click the play icon button and watch the diffs of the states appear and their relationship to what's being rendered onto the screen. Another cool thing is that you <strong>DONT HAVE TO DO THEM IN ORDER</strong>. For example, you can jump to action 1, then jump to action #4 to see the outcome. That's time traveling in a nutshell, the ability to go forwards and backwards in state to see the effects of an action on your store.
<img alt = "diff replay on Redux-DevTools" src = "https://thepracticaldev.s3.amazonaws.com/i/r0ti9f9btgrf83v0k8jx.gif"/>
<figcaption>Hey DJ, bring it back!</figcaption>
 <br/> 
<strong>Pro-Tip:</strong> Remember our <strong>"chart"</strong> sub-option from earlier? You can time travel with that option selected as well, which will re-draw the chart in real-time as the mutations as occurring during your playback. You can witness this below. 
<img alt = "chart replay on Redux-DevTools" src = "https://thepracticaldev.s3.amazonaws.com/i/842ly8bak7tdrxodqt2l.gif"/>
<br/>
<figcaption>Time Traveling Chart</figcaption> 
</p>
<hr/>
<h1>Woohoo, we successfully time-traveled, but what about ReSelect?</h1> 
<img width = "60%" alt = "Dr.Emmett Brown from Back to the Future" src = "https://media.giphy.com/media/Vqvr9BGv1vhDi/giphy.gif" />
<p> Ah yes, I almost forgot about the ReSelect library and how that can assist us. For brevity I'm going to do a quick overview, and then a more in-depth tutorial in an upcoming post.<br/>

First, <a href = "https://github.com/reduxjs/reselect">lets define what the ReSelect library is</a>, and how it works. ReSelect allows you to define functions known as <Strong>Selectors</Strong> that uses a concept in Computer Science known as Memoization (Mem-Oh-Ih-Za-shun) which allows us to take advantage of computed values not having to be re-calculated unless there's a significant delta (change) in the expected result. Selectors can be created from other selectors as well, so if a result is dependent or can be derived from another previously created selector, then you can pass it to your new selector to return the upcoming state value. In Redux this is beneficial because we no longer have to view the entire store, when accessing the future state, but instead <strong>only pay attention to the specific portion of state that we care about</strong>. In addition, this helps with limiting side-effects resulting from state being updated in your store, which would cause a flush of props to your component structure when it probably only cares <strong>about a specific part of state</strong>. For example, if you had a store such as:<br/>
<code>let exampleState = {
  shop: {
    taxPercent: 8,
    items: [
      { name: 'apple', value: 1.20 },
      { name: 'orange', value: 0.95 },
    ]
  }
}</code><br/>

If your component only cared about the taxPercent property on the store, passing the entire state of the store down is useless. Instead, ReSelect would allow you to target and pass only the taxPercent property by doing the following: 

<code>const taxPercentSelector = state => state.shop.taxPercent</code><br/>

If you were to read this code aloud, it would say "access my the current state of my store object, within the shop property, and return to me only the tax percent property". To put it all together, this would need to go <strong><a href= "https://github.com/reduxjs/reselect#containersvisibletodolistjs">into your connect() HOC's mapStateToProps function</a></strong> Unless this value changes, it will be immediately and readily available in your container/component hierarchy via props for use. <br/> 

In addition, memoization of computed values are done as described below: 
<code>
const taxSelector = createSelector(
  subtotalSelector,
  taxPercentSelector,
  (subtotal, taxPercent) => subtotal * (taxPercent / 100)
)
</code><br/> 
The above would calculate and return the value of tax on a item based off the value derived from the subtotal and taxPercentage selectors. Notice the createSelector() method that takes in the other selectors - it allows for composability(compose-ability) of values to be computed quickly and only re-computed when there's a delta in the previous result.<br/><br/>

<img alt = "Crazy Dr.Brown from Back to the Future" width = "60%" src = "https://media.giphy.com/media/yPO3Yxx3jRSlG/giphy.gif" /><br/><hr/>

<strong>Give it a try:</strong> You can play around with the selectors available in our boilerplate via the <code>app\containers\HomePage\selectors.js</code> path. Don't be afraid to break them apart, and reconstruct the. to learn more; it's apart of the learning process!

 <hr/> 

All this being said, I highly recommend using ReSelect in your application to cut-down on the amount of props being passed to all your components, which can assist in performance by cutting down on useless renders.<br/>
 <strong>Pro-Tip:</strong> Renders should only happen on prop or state changes that are applicable to that particular component's functionality/data integrity
</p>
<h1>Our future is now looking bright!</h1> 
<p>
  While this was a quick overview to get you going with improving your debugging of Redux actions and state, I encourage you to continue expanding your knowledge of the tools and libraries mentioned above to improve your codebase. I also encourage you to do a quick google search for more information/tutorials available on this topic, <a href = "https://medium.com/the-web-tub/time-travel-in-react-redux-apps-using-the-redux-devtools-5e94eba5e7c0">such as this great tutorial by Onsen UI & Monaca Team covering the Redux-DevTools and time-traveling more in-depth.</a> Thank you for coming back to another, but not last tutorial; feel free to leave any comments, suggestions, ideas, feedback for my next tutorial. 
<img src = "https://media.giphy.com/media/J2oFWZdalFZmM/giphy-downsized.gif" title = "keep challenging yourself"/>
</p>