What's Redux and how to use it? Redux Series I

Introduction

Redux is a global state management object for your react app. It’s basic idea comes from the flux architecture. We Need to redux because as our react app gets bigger. It’s hard to manage our state. If two child component share the same state from parents. The child must pass the state back to parent and then to the other child component. To solve this problem, we need a global store.

React Child Component with and without Redux

Now with redux, we just need to change the state in our redux and all the react component will automatically be updated.

SO How do we use it.

I’ll use one of my demo app as in example. First we need to identify an action type. It is basically a string but we defined it as a variable. We do this for best practice so we don’t make typos.

1
2
//Action Type
export const ADD_RECIPE = 'ADD_RECIPE';

Now we identify our action. Here we call our action types and our payload(data that we want to send to our state.)

1
2
// action.js
export const addRecipe = recipe => ({ type: types.ADD_RECIPE, recipe })

Next we pass the recipe to our reducer to add to our state. And our state is now updated!! yay!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//reducer_recipes.js
const initialState = [
{name: 'Sushi', ingredients: ['3 tablespoons rice vinegar', '4 sheets nori (dry seaweed)', '1/2 cucumber, sliced into thin strips']},
...
];

export default function(state = initialState, action){
switch (action.type) {
case ADD_RECIPE:
return [
...state
,
{
name: action.recipe.name,
ingredients: action.recipe.ingredients
}
]
default:
return state
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// reducers/index.js
// Now we export our reducers.
const rootReducer = combineReducers({
recipes
});

export default rootReducer;
//index.js
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

Here’s a diagram on how redux works. I also attach two examples with demo site that uses redux.

Redux Flow chart

This is it for redux. You can connect redux with jquery for plain javascript. Next I’ll talk about how to connect redux to our react component in the next blog post.