The 3 pillars of Redux

Image from instagram

Note: This is just a friendly introduction to Redux. Not a complete guide

Redux, simply put, is a state management library for JavaScript applications.

It can be used with almost any JavaScript based framework but it’s most commonly used with libraries/frameworks like React and Angular.

It has 3 main components:

  1. Actions
  2. Reducers
  3. Store

Add a fourth component of ‘View’ and you get the 4 components of Facebook’s Flux architecture.

Redux = Reducer + Flux

But as Redux is more commonly used with other JavaScript frameworks/libraries for building user interfaces which constitutes the View layer of the Flux architecture, we’re left with the 3 components of Flux which constitute Redux.

Actions

An action is just a plain JavaScript object, containing an action type and the action payload. In simpler terms, it’s just a message, telling the reducer what to do and provide any data that might be needed to do that.

{
	"type": "ADD_TODO",
	"payload": {
		"title": "I am a new to-do"
	}
}

Reducers

A reducer is a pure function that ‘reduces’ the current state to some other state.

What’s a pure function? It’s a function which has no side-effects. Meaning, given the same input, it’ll always give the same output.

What does ‘reducing’ the current state mean? A reducer takes input from the action and changes the state as instructed by the action and sets that as the new state.

One main thing to note here is that state in Redux is immutable, that means it can’t be modified. So if you can’t edit a state, you copy the state, make changes to it and set it as the new state.

const Todos = (
  state = {
    todos: [],
  },
  action
) => {
  switch (action.type) {
    case ADD_TODO:
      return {
        ...state,
        todos: state.todos.concat(action.payload),
      };
    case ActionTypes.EDIT_TODO:
		...
    case ActionTypes.REMOVE_TODO:
		...
    default:
      return state;
  }
};

Store

A store is where all the state of your application resides. You can have one big state for your app or you can make individual reducers have their own states. More often than not, you want your reducers to maintain their own state.

Notice in the reducer above the state only has todos, similarly the ListsReducer may have lists as its state and we can combine these reducers to create our redux store. This makes it easier to separate out the concerns as each reducer only plays with its own state.

const store = createStore(
  combineReducers({
    todos: TodosReducer,
    lists: ListsReducer
  })
);