Getting Started with Redux: Part 1

We create open-source because we love it, and we share our finding so everyone else can benefit as well.

Getting Started with Redux: Part 1

Many articles tend to be focused around redux being a part of the app’s foundation. For anyone getting started with redux, I would love to give new-comers a great place to start. In this 3 part guide, we cover the react/redux concept, practices, and application. Will will also add Redux to an existing React app, and make it better in the process.

Without a doubt redux has made a huge impact on the JavaScript ecosystem. So, it is an understatement to say Redux is nothing short of amazing when working with reactive JS applications.

<code>https://www.youtube.com/watch?v=xsSnOQynTHs</code>

Two years after the initial release, and Redux almost feels like a rite of passage for reactive JavaScript, regardless of Frontend framework used. Redux is simple once you understand the concepts. So without further adieu let’s learn Redux!

It’s All About That State

With React we have two major elements of our application, one being our state. We use state to keep track of constantly changing values for our app. These are values like the contents of an input box in a form, the total showing in a counter, and any other dynamic value our app depends on. As programmers this makes it easy to see if everything is working correctly. It also helps avoid needing to worry about garbage collection. In addition we inherit a mindset to keep this state concise, consolidated, avoiding convolution.

Give Props to Props, and State to State

The other element within React Props, is similar to a newcomer when compared to state that its concept tends to throw people off at first. So many find themselves asking “what is the difference between state, and props”. To many and working with other languages these two elements do seem like the same thing, since they sort of act the same at first glance. You can assign data to each, and you can pass both around the application with the stored data, but it is their functionality and limitations that set them apart causing a better application overall.

To quickly summarize, State exists to store the state and constantly changing mutable data of your application, where Props are there as a place to access elements that are usually static, and can help create state. Think of props as the direct line to the static or property data that is not meant to be changed, and state is that data is constantly changed, like if a button has been pressed, or text entered into that input field.

Keep in mind we are not even skimming the surface of discussing external data you may want your application to interact with, but I want to make that clear as it is not very apparent when starting out. We will get there though!

Do You Need Redux?

One rule that has been famous since the release of Redux has been, “if you don’t know if you need redux, chances are you don’t“, or something to that effect. Of course there is a bit of a paradox in this statement, because if you don’t even know how it can help how could you possibly know if you need it? You could write an incredibly intricate React application with the usual uni-directional flow, and may never know if you need redux, all because you were told you didn’t need it if you weren’t sure. I think I would revaluate the marketing team for that slogan.

Still the question stands, especially those new to redux, “Do I need Redux?” Let me start by answering with, “More than likely!“. It does depend on the size of your project, and how much state, and how many actions you handle in that application, either way you will certainly need it in time. Before we get too deep into that we should really discuss what redux is for, and why we want to use it in our projects.

What Redux Offers

Normally I recommend the documentation for projects like this, but it is extremely easy to get lost in the documentation, even as someone using redux; the documentation is so thorough, almost long-winded that it is not something you could read in a day. To spare you all of the gruesome details let us go through a hypothetical situation to explain the need for redux:

Imagine having a React-based project made of several different root components, each with several methods, all using several state entries, and the structure is setup so each component can use the methods from another. To make it even more convoluted they all share a commonality of using a shared API. If you can imagine an app like that, you can also imagine the amount of organization that would be required to make all of this work smoothly without repeating code.

This is not the situation you need to look for to decide if you should use redux, but it does help point out the need for Redux. To quit beating around the bush, Redux allows us to easily organize our methods, including API calls, all of our state, as well as how we want our actions to be interacted with. What we are doing  is removing the constraints of components, and make them controllable across the entire app. There are many more features that make Redux great, but the overall ability is really that simple, but with the way it’s presented elsewhere you probably wouldn’t ever guess.

What Else Redux Does

Saying that organization of code and easy scalability of apps is all that redux does would be fairly ignorant. One of the high points is how Redux continues to hold React within the Functional Programming paradigm. This functional-based platform shows the benefits of an immutable setup including time travel of state changes. That can be confusing to new-comers, but let’s look at an example:

Your app has a single button. When pressed it shows a message, as well as changes the color of the button. While the button is in its second color, pressing the button again changes the background color. Three seconds after the second click the background-color and button color return to their original colors, and the message goes away.

Redux Dev Tools
Redux Devtools

To accomplish this we maintain state, keeping track of our events. Such events like how many total times the button is pressed, the button color, background color, and time passed after the second click. Without Redux we would need to change each of these values in our state. The previous values would also be lost when changed. Redux keeps a record of our state change and in turn allows us to reverse the state changes. This not only helping us with creating our app, but also debugging our app as well.

 // how we change state with the current state
return {
  ...state, stateChange: change
}

Looking at the above you can see that each time state changes we pass the state as a parameter. After that we pass the change that needs to be made. Actually, a new state object is being created with each change. This way the previous state is constantly preserved. The Redux Dev-Tools are important for giving us access to “Time Traveling”. With this you can go back and forth through state changes. We can also reset, and commit changes.

We are only starting to learn and understand Redux, so we have options to make it even better. Such options like implementing Immutable.js with redux.

Why You Shouldn’t Use Redux?

With all of this awesome ability you may be asking yourself, “why would I not want to use redux all the time”? While you could use redux for all of your projects there is a down-side. The increased amount of code as well as complexity that comes with implementing Redux within your app.

To give you an idea of what is ahead here is my own redux boilerplate without any app code in it at all, and you should be able to see that there is quite a bit of code just to have Redux in place. To use Redux you need to create an action for each method, a new listener in the reducer, whatever state you need in your store, and then tie all of that into your app. There are always certain situations where this is not entirely true. We will revisit this when we get to those situations.

Understanding the Redux Structure Without Code

Before we jump into the actual code let us step back a moment and look at Redux. Redux can be added using various different layouts. While an idiomatic structure is fairly popular, I prefer a scaffolded layout as it provides more context.

These are the folders we will see for the entire app:

Actions: Our Redux actions folder

API/Lib: All of our API-based and external library files

Components: Where to add our React components

Containers: Redux containers (routing components)

Reducers: Where the Redux reducers will live

Store: Our initial state and updated Redux functions

Styles: All styling files including CSS/SASS/LESS, and other style-based files

Important Redux Files

The entry point file, or index.js file, is often found in our app folder. In this case that folder is named react-app:

index.js

  • we will provide the Redux store to the rest of the app here, making state excessable
  • being the root of our app we can also include our redux-dev-tools, and routing

store

  • our entry-point for state we need to share such, so we create a store of default keys and value
  • our store will also load our middleware including the dev-tools

actions

  • the functions our components use will be found here
  • if we have APIs to interact with we can import such here

reducers

  • this is our Redux brain which handles the default state, and changes it when needed based on dispatched actions
  • reducer filters listen for the actions and change state based on the action

components

  • these are our views which our users interact with
  • our components import the state, and actions
  • our components can also dispatch actions

containers

  • we can use containers to call multiple sub-components within a component that may or may not need state
  • containers are not a necessary type, but simply something to be aware of.

We can place these functions anywhere in our app. The main takeaway is how our app is taking advantage of redux when incorporated.

The Workflow

With everything in place, we will be dispatching actions from our Components, our action controllers will then call the Action, the associated Reducer will intercept the dispatch, create a new State object, and then the view will Render with the new state. That’s it!

In part 2 we will move on to the code and look at how to put Redux into practice.

Next: The Beginner’s Guide to Redux: Part 2

 

No Comments

Add your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.