7 min read

Have you tried using React and now you want to increase your abilities? Are you ready to scale up your small React app? Have you wondered how to offload all of your state into a single place and keep your components more modular?

Using Redux with React allows you to have a single source of truth for all of your app’s state. The two of them together allow you to never have to set state on a component and allows your components to be completely reusable. For some added sugar, you’ll also learn how to leverage Firebase and use Redux actions to subscribe to data that is updated in real time.

In this two-part post, you’ll walk through creating a new chat app called Yak using React’s new CLI, integrating Redux into your app, updating your state and connecting it all to Firebase. Let’s get started.

Setting up

This post is written with the assumption that you have Node.js and NPM already installed. Also, it assumes some knowledge of JavaScript and React.js.

If you don’t already have Node.js and NPM installed, head over to the Node.js install instructions. At the time of writing this post, the Node.js version is 6.6.0 and NPM version is 3.10.8.

Once you have Node.js installed, open up your favorite terminal app and install the NPM package Create React App; the current version at the time of writing this post is 0.6.0, so make sure to specify that version.

[~]$ npm install -g [email protected]

Now we’ll want to set up our app and install our dependencies. First we’ll navigate to where we want our project to live. I like to keep my projects at ~/code, so I’ll navigate there. You may need to create the directory using mkdir if you don’t have it, or you might want to store it elsewhere. It doesn’t matter which you choose; just head to where you want to store your project.

[~]$ cd ~/code

Once there, use Create React App to create the app:

[~/code]$ create-react-app yak

This command is going to create a directory called yak and create all the necessary files you need in order to start a baseline React.js app. Once the command has completed you should see some commands that you can run in your new app.

Create React App has created the boilerplate files for you. Take a moment to familiarize yourself with these files.

.gitignore
  All the files and directories you want ignored by git.

README.md
  Documentation on what has been created. This is a good resource to lean
  on as you're learning React.js and using your app.

node_modules
  All the packages that are required to run and build the application up
  to this point.

package.json
  Instructs NPM how scripts run on your app, which packages your app
  depending on and other meta things such as version and app name.

public
  All the static files that aren't used within the app. Mainly for
  index.html and favicon.ico.

src
  All the app files; the app is run by Webpack and is set up to watch all
  the files inside of this directory. This is where you will spend the
  majority of your time.

There are two files that cannot be moved while working on the app; they are public/index.html and src/index.js. The app relies on these two files in order to run. You can change them, but don’t move them.

Now to get started, navigate into the app folder and start the app.

[~/code]$ cd yak
[~/code/yak]$ npm start

The app should start and automatically open http://localhost:3000/ in your default browser. You should see a black banner with the React.js logo spinning and some instructions on how to get started. To stop the app, press ctrl-c in the terminal window that is running the app.

Getting started with Redux

Next install Redux and React-Redux:

[~/code/yak]$ npm install --save redux react-redux

Redux will allow the app to have a single source of truth for state throughout the app. The idea is to keep all the React components ignorant of the state, and to pass that state to them via props. Containers will be used to select data from the state and pass the data to the ignorant components via props. React-Redux is a utility that assists in integrating React with Redux.

Redux’s state is read-only and you can only change the state by emitting an action that a reducer function uses to take the previous state and return a new state. Make sure as you are writing your reducers to never mutate the state (more on that later).

Now you will add Redux to your app, in src/index.js. Just below importing ReactDOM, add:

import { createStore, compose } from 'redux';
import { Provider } from 'react-redux';

You now have the necessary functions and components to set up your Redux store and pass it to your React app. Go ahead and get your store initialized. After the last import statement and before ReactDOM.render() is where you will create your store.

const store = createStore();

Yikes! If you run the app and open your inspector, you should see the following console error:

Uncaught Error: Expected the reducer to be a function.

That error is thrown because the createStore function requires a reducer as the first parameter. The second parameter is an optional initial state and the last parameter is for middleware that you may want for your store. Go ahead and create a reducer for your store, and ignore the other two parameters for now.

[~/code/yak]$ touch src/reducer.js

Now open reducer.js and add the following code to the reducer:

const initialState = {
  messages: []
};

export function yakApp(state = initialState, action) {
  return state;
}

Here you have created an initial state for the current reducer, and a function that is either accepting a new state or using ES6 default arguments to set an undefined state to the initial state. The function is simply returning the state and not making any changes for now. This is a perfectly valid reducer and will work to solve the console error and get the app running again.

Now it’s time to add it to the store. Back in src/index.js, import the reducer in and then set the yakApp function to your store.

import { yakApp } from './reducer';

const store = createStore(yakApp);

Restart the app and you’ll see that it is now working again! One last thing to get things set up in your bootstrapping file src/index.js. You have your store and have imported Provider; now it’s time to connect the two and allow the app to have access to the store. Update the ReactDOM.render method to look like the following.

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Now you can jump into App.js and connect your store. In App.js, add the following import statement:

import { connect } from 'react-redux';

At the bottom of the file, just before the export statement, add:

function mapStateToProps(state) {
  return {
    messages: state.messages
  }
}

And change the export statement to be:

export default connect(mapStateToProps)(App);

That’s it! Your App component is now connected to the redux store. The messages array is being mapped to this.props. Go ahead and try it; add a console log to the render() method just before the return statement.

console.log(this.props.messages);

The console should log an empty array. This is great!

Conclusion

In this post, you’ve learned to create a new React app without having to worry about tooling. You’ve integrated Redux into the app and created a simple reducer. You’ve also connected the reducer to your React component.

But how do you add data to the array as messages are sent? How do you persist the array of messages after you leave the app? How do you connect all of this to your UI? How do you allow your users to create glorious data for you? In the next post, you’ll learn to do all those things. Stay tuned!

About the author

AJ Webb is a team lead and frontend engineer for @tannerlabs, and the co-creator of Payba.cc.

LEAVE A REPLY

Please enter your comment!
Please enter your name here