How To Manage State With Redux

Creating a counter app with React and Redux from scratch.

EarthCtzn
9 min readMar 12, 2020
Photo by Christina Morillo from Pexels

Hello everyone, thanks for stopping by! Today, we will build a simple React.js application that displays a counter with two buttons. The counter will go up by one when you click the “up” button and down by one when you click the “down” button. We will be going through the steps to set up our environment and creating our counter app. Let’s hop to it!

1 - Create The Directory For The Application

Decide where you want your application files to live then create the directory for it. I will name my directory ReactStateDemo.

mkdir ReactStateDemo

2 - Navigate Into That Directory

cd ReactStateDemo

3 - Set Up Environment

We will need to make sure we have Node.js and NPM installed.

NPM — Node Package Manager is a command-line tool for handling packages of reusable JavaScript code.

Node.js — Node is a JavaScript runtime, allowing JavaScript to be run on your computer, instead of in a browser. Make sure you are using the latest versions by running:

// Check Node version
node -v
// Check NPM version
npm -v
// If NPM is outdated
npm install -g npm

If you have it installed you should see something like this on the terminal.

If you don’t have Node installed, you can use the Node Version Manager to install Node.js and keep it updated.

4 - Create The React App

Once you have all of the above ready, run:

create-react-app your-app-name-here

Once that is done, you should see something like this.

5 - Install Necessary Packages

Now, make sure you are in the same directory as the app.

Once there you will need to run:

npm install react-redux
//followed by
npm install redux

This will add these packages to your package.json file.

Running all these commands will build out all the necessary files and directories for us as seen below, drastically reducing the time it takes to start up a working app.

6 - Start The Application

Now, we can run yarn start to get the application running. This is a good spot to bring up the fact that React was created by the developers at Facebook so the intention is not necessarily getting up and running quickly, but to be able to easily build and maintain large web applications. This is achieved by working with components; think of them as small pieces of a big puzzle. That said, we will be importing and exporting many different components in our app.

One advantage is, that this allows you to easily find any bugs depending on which component is showing errors etc. You will see this a bit more clearly as we move along.

7 - Remove Boilerplate Code

Let’s get this going. First, I like to remove any files that I will not be using. In this case, we will not be using the serviceWorker.js, setupTests.js , index.css, or App.test.js files so we can remove them. Now, let’s clean up our boilerplate code so we can start working on our app.

Our index.js file currently has some code we will not be using. It looks something like this.

Since we removed the serviceWorker.js as well as the index.jsfiles we do not need to import them. So we’ll remove lines 3, 5, and lines 9 through 12 in the image above.

We will continue cleaning up our boilerplate code in the App.js file and remove pretty much all of the code in the App() function.

We will remove line 2 above since we won’t be using the logo and lines 9 through 20 above. This will leave us with a dark gray background when the app is running.

This is a great place to push your code. I am using GitHub for my repository.

8 - Add Some Basic Code

On line 9, we will be writing the code that will display on the screen. For now, I will add an <h1> tag with “Hello World!” as its contents.

Here is what you should see on the browser.

9 - Create Actions File

This is a great place to start creating the actions our app will use to add or remove data from our Redux store. This app will only have two actions. One for incrementing the counter and one for decrementing the counter.

We will create a new file called counterActions.js NOTE: In this app, we don’t need to structure our file tree so much as there are only two actions in one file. In a larger application, you will see the following structure.

In the actions directory, you would see a file for each component that uses any actions i.e loginActions.js , reviewActions.js , tweetActions.js etc. For our demo, we will create a counterActions.jsfile in the src directory along with all our other components.

On the terminal run:

touch src/counterActions.js

Inside these action files is where we would have all action creators and any other functions that fetch data from external APIs like your own rails backend.

10 - Create Actions

What are actions?

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().

Actions are a simple function that returns an object. The object has a type: attribute with the value of the action to be taken. Inside the counterActions.js file, add the following code.

11 - Create The Reducer

What is a Reducer?

Reducers specify how the application’s state changes in response to actions sent to the store. Remember that actions only describe what happened, but don’t describe how the application’s state changes.

Let’s unpack this a bit. The reducer is a function that takes state and an action as arguments. This is where we set our initial state object. In our app, we set our default state to be an object with a key named count: with a value of 0 . Inside the function, we have a switch statement that does something based on the value of the key of action received.

To maintain the immutability of our state, we use the spread () operator to make a shallow copy of our previous state and operate on that. If the type is ‘ADD’ then we add 1 the value of count and vice versa.

12 - Import Components & Create Redux Store

We almost have all we need. Now, let’s import all the components we need for our app to have a store.

1 — Import the createStore component from redux

2 — Import the Provider component from react-redux.

3 — Import our counterReducer.js file

4 — Create our store.

To create the store, we set a variable equal to the createStore() method and pass in our counterReducer component as an argument (line 8 above). Then, we will need to place the <App> component inside the imported <Provider> component(line 12 above). Then we pass the <Provider> our newly created store as a prop(line 11 above).

13 - Import Redux Dev Tools

To be able to view the contents of our redux store, we will want to use the Redux DevTools. To do so, we add the following argument to our createStore() method(lines 12 and 13 below).

Notice we added lines 12 and 13 to access our redux dev tools.

14 - Add Code

We are almost done! Now we just need to build out our counterInput.js component. This component will render our buttons and the current count from our redux state.

Here we have a simple class component that renders two buttons:

15 - Connect The Components

We need to import a few more components to be able to get this all connected. We also need a way to display the number of times the button has been clicked. We will start with the connect component from react-redux (line 2 below). This is what will grant us access to the store and other components in our app.

Notice on line 25 above that we are wrapping our app with the connect component and passing in null as one of the values. This is because we are not yet accessing the store. We need a few more things.

16 - Import Actions

Here, we import the actions we created earlier.

We have to also include them in our connect statement at the bottom of the file.

Here we have imported our actions on top and used some destructuring to include our actions.

17 - Add Event Listeners & Display Count To User

On line 21 below, we use a simple <h1>tag to display the current count to the user. On lines 24 and 29 below, we added onClick event listeners to our buttons that point to our new handleOnClick() function.

On line 21 above, we have hard-coded the number 5 for now.

The handleOnClick()function will trigger an action based on the events’ target name. In this case, the targets are the buttons and the names are “up” or “down”. If the click targets’ name is “up” then the increaseCount() action will be dispatched if not then the decrementCount() action will be dispatched.

Here is what the counterInput.js file should look like at the moment.

18 - Connect CounterInput Component To The Store

We are now ready to show our users the count. To do this, we will need to access the Redux store. We do this by using the mapStateToProps() function which will, as the name implies, map our state to our props making the Redux store available to this component.

On line 35 above, we add the mapStateToProps() function and pass it in as an argument to connect() on line 40. Now, we can access the current count from the store by calling this.props.count as we do on line 21 below.

19 - Import Input Component

Our final step is to import this component into our App.js file in place of our “Hello World!” message.

You should now see this on the browser:

And there you have it! Now, whenever we click the “Up” button the counter goes up by one, and when we click the “Down” button the counter goes down by one as does the redux state. Here is a video of the working counter.

I hope this was helpful! Let me know your thoughts in the comments! Stay healthy, stay curious!

--

--

EarthCtzn

Full-Stack web developer having fun with Rails, JavaScript, HTML, CSS, React, Redux, Bootstrap, and making things.