Redux Fundamentals

Untitled Document.md

Redux Fundamentals

In this article we will learn basics of redux application by going through a simple application.

Three principles of Redux

  • Store
  • Actions
  • Reducers

Store can be thought of a single big object tree, where data of entire application is stored. Actions are nothing but javascript objects which consists of type and payload. Type is the intent for example ADD_USER and payload is the data. Reducer is a pure function which decides what is supposed to be done with the payload.

We will be writing code in /src/app.js file, which we created in the previous article on setting up react and redux application. Let’s look at the code:

import { createStore } from 'redux';

// STEP 3: Define Reducer
const reducer = function(state = {}, action) {
  switch (action.type) {
    case 'ADD_USER':
      return state = action.payload;
      break;
    default:
  }

  return state;
}

// STEP 1: Create Store
const store = createStore(reducer);

store.subscribe(() => {
  console.log(store.getState());
});


// STEP 2: Dispatch Actions
store.dispatch({
  type: 'ADD_USER',
  payload: {
    'username': 'mashwin',
    'email': 'mashwin@gmail.com'
  }
});

In step one we create a redux store, by passing it a reducer. In the second step we dispatch an ADD_USER action, which will store user data in the store. In the third step we create a reducer function which takes in state and action. We initialize state to an empty object. The ADD_USER case assigns the payload to the state.
The subscribe method logs the current state of our application. When we refresh our page we will see user data in the console.

The git repository for the application can be found here: Simple Redux Application

This is a very simple example, but it helps us understand the three principles of Redux.

Comments