Redux/Saga + create-react-app
For Medium readers, I provide a Udemy course How to Start React Project: Best Practices for 9.99$. The goal of this course is to share with you my findings of the last few years about what steps and decisions are better to make at the beginning of development so that you will have a good starting point for your new project.
In this article, we will make a newly created react app suitable to work with redux and redux-saga. All source code you can find here.
Create React App
Create react app is the most popular starter for React projects maintained by Facebook.
$ npm install -g create-react-app
$ create-react-app <PROJECT_NAME>
$ cd <PROJECT_NAME>
Redux is a great tool for application state management. I also take the redux-act library to make actions and reducers more concise and readable. With this library you will write actions and reducers this way:
$ npm install --save redux react-redux redux-act
Also, recommend two libraries to use with redux. It is redux-devtools-extension and redux-form. The first one allows you to see the state and its changes in chrome extension. The second one simplifies work with forms — must-have if you have a lot of them.
$ npm install --save redux-devtools-extension redux-form
Redux-saga is a library that helps you to work with async code, such as requests and background app work. It is better to read some tutorials about redux-saga first if you don’t know what it is. In short terms, you subscribe generator function to action, and when this action occurs, it will trigger your saga. In this generator function, you can make all the work you don’t do in the reducer.
$ npm install --save redux-saga
Put everything together
We will keep all the reducers and actions in separate directories.
In the directory with reducers, we will create index.js file which will have references to all reducers.
After that, we will create a redux store for our app.
Next, we will create middleware.js file for redux-saga.
When we have sagas and reducers in place, it is time to put everything together.
Saga and actions
As I mention earlier, to run saga you need to subscribe to action first.
In the code snippet above, you can see it is a little bit tedious to connect each action to an appropriate saga. To make it cleaner, when we need to subscribe for a specific action we go through these steps: create the file in sagas directory with the same name as the file with action declaration. Then in the newly created file make saga with the same name as the action name. By using this convention, we can go through each batch of actions and sagas pair and connect them in a loop.
State and components
Also, I want to show you the function with which you can connect the component to the store easier.
Reach the next level of focus and productivity with increaser.org.