React-Redux Tutorial for beginners 2018 with cutting edge versions of simple examples

Zheng Yang
FullStack-Microservices-Developers
6 min readJan 29, 2018

Original Article at: https://medium.com/@zhengyang_72813/react-redux-tutorial-for-beginners-2018-with-cutting-edge-versions-of-simple-examples-f1b20e93bdf6

Recently, a lot of new graduated developers just emailed me and asked about where to start of learning React-Redux. They mentioned the difficulty to search a tutorial with simple demo code and explanation, while most of the existing tutorials are focusing on the concepts of Redux, which are very hard to understand as a beginner.

That’s the motivation of this article, to give you an complete structure of React-Redux project with just simple components within it. Easy to understand, expand friendly.

With this tutorial, I’m going to show what React-Redux developers care about and demonstrate how to scaffold a react-redux based project from facebook official create-react-app, as well as how to expand it into an React-Redux front-end application.

You will be afterwards very easy to integrate the front-end app with any type of REST backends(such as express in JS or Pyramid in Python, see more details from the tutorial, Create RESTful backend with ExpressJS(Nodejs) in 5 mins)

0. Prerequisite

Please notice before you start, this article assumes that

1) You already have the very basic knowledge of Javascript.

2) You know the concept and workflow of React. By the cutting edge of Redux, though this technology is a state management framework that can exist without react, react is still the best library to work with Redux.

But if you are new to React as well, no worries, here we have another tutorial for React, Understanding React from one article, and that’s Enough.

1. Getting started

Install create-react-app, the Facebook official scaffold, by executing the following commands on your Terminal(for Mac) or Command Line(For Windows). Please note, you will need to use administration privilege to install globally.

npm i -g create-react-app

2. Install Dependencies

Open the file package.json and modify dependencies as below, which is to import redux, react-redux, and react-router-dom as we may always need routing on our applications.

"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.0",
"redux": "^3.7.2",
"redux-form": "^7.2.1"},

3. Scaffold Project Structure

It will become quite straight forward to scaffold the structure and create components once you got familiar with how Redux works for storing states and reflecting changes. See the flow chart of Redux:

Obviously, the workflow is running with four parts: Store, Actions, Components, Reducers, while actually React-Redux separates Components into two parts: Components & Containers for UI design and functional logic respectively.

Actions

The transfer unit to pass request and data to store and have relevant states changed afterwards.

Store

Store is where you store the states, you can understand it as an warehouse. Each app has only one store. So, you can create an empty store.js under src directory. Just leave it empty and we will discuss what to fullfill later.

Components

The UI template.

1) Has only UI presentation, no business or functional logic included.

2) No state, DO NOT use any this.state within Components Instead, all the data is mapped from this.props provided from containers

3) No Redux API is allowed

Containers

On the contrary of Components, it is where the states being managed for each components, also providing methods to generate actions.

1) Data and methods only, NO UI designs

2) manage states

3) dispatch actions & mapped states to Components

Reducers

After receiving an action, Your store need to provide a new set of states to have the new view on the client-side. Reducers play the role to recognize the type of actions and deal with the data, as well as generating the new states. Reducers are the hardest worker, who mostly deserve a huge KPI bonus for attending every piece of work during the whole process. :)

So, guess now you can just straight forward and create such directories, which are src/actions, src/components, src/containers, src/reducers, and don’t forget store.js, just like that shown below:

4. Create reducers and combineReducers

For example, we can create a CountReducer which provides action handling methods for dispatchers:

src/reducers/CountReducer.js

export default function CountReducer(state = {
count: 0, wish_value: 0,}, action) {
const count = state.count const wish_value = action.wish_value switch (action.type) {
case 'increase':
return {count: Number(count) + 1}
case 'update':
return {
count: wish_value, }
default:
return state
}
}

From my perspective, it’s always a good way to create an index reducer at src/reducers/index.js with a combineReducers to combine all the reducers within src/reducers folder. Why? You will be able to load all the reducers at once and never change store.js. You can alternatively put combineReducers at store.js, fully up to you.

src/store.js

const reducer = combineReducers({
CountReducer
});

const initialState = {
CountReducer: {count: 123, wish_value: 12}
};

let store = createStore(reducer, initialState);

5. Create store

Create Store and export, which will be imported into <Provider>, at the next step.

import {createStore, combineReducers} from 'redux'import CountReducer from './reducers/CountReducer'const store = createStore(CountReducer);export default store;

6. Then go back to finishing src/index.js

Define Provider at src/index.js with imported store object form store.js.

I’d extremely love to define BrowserRouter at the top of <App />, so as to allow us using <Route> anywhere of the containers.

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

7. Build the first Container

Let’s start from Containers since containers are the core managers of each components. The design of components will become easier once you have your data and methods defined, doesn’t it?

There are two redux defined core methods of each container: mapStateToProps and mapDispatchToProps: among which mapStateToProps responsible to load states from store and map them into components’ props, while mapDispatchToProps is to send action to reducers.

You should go ahead and define those at the very first:

// Map Redux state to component propsfunction mapStateToProps(state) {
return {
value: state.count,
wish_value: state.wish_value
}
}

// Map Redux actions to component props
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(actions.increaseTodo()),
onUpdateClick: event => dispatch(actions.updateTodo(event.target.value)),
}
}

Then connect those two methods to our component:

// Connected Componentconst VisibleCounter = connect(
mapStateToProps,
mapDispatchToProps
)(Counter);

8. Design component: (src/components/Counter.js)

Simple and easy component with input text field and button

export default class Counter extends Component {
render() {
const {value, onIncreaseClick, onUpdateClick} = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
<input type='text' onChange={onUpdateClick}/>
</div>
)
}
}

9. Actions, the bullet of the whole process

After finishing all the components, containers, reducers, we need a carrier passed from containers to reducers and let store to change states.

Here is a sample action: (src/actions/index.js)

//Action Creatorexport const increaseTodo = () => {
return {
type: types.INCREASE_TODO,
}
}
export const updateTodo = (wish_value) => {
return {
type: types.UPDATE_TODO,
wish_value: wish_value,
}
}

You are all set! Access the root directory through Terminal/Command Line, and run: npm start

All the code base is available on Github repository:https://github.com/river7527/React-Redux-Tutorial-for-beginner-2018

If you like this tutorial, please give me a star, which will motivate me a lot. Thanks.

River YANG

--

--