Skip to content

Instantly share code, notes, and snippets.

@SantoshCode
Created April 17, 2021 04:14
Show Gist options
  • Save SantoshCode/5dd7eb792b00ee167898bf648b35d2b2 to your computer and use it in GitHub Desktop.
Save SantoshCode/5dd7eb792b00ee167898bf648b35d2b2 to your computer and use it in GitHub Desktop.
How redux works?

Redux

Redux is based on FLUX application architecture (by Facebook)

Building Blocks of Redux are:-

  • Action Javascript objects that represents what just happend. We could also call them Events e.g. userAdded, userUpdated, userRemoved

  • Store This is single javascript object that includes our application state e.g.

      {
        category: [],
        user: [],
        cart: [],
      }
    
  • Reducer Responsible for updating the slice of the store. They are simply Event Handlers. They are pure functions so they don't mutate global state. They just get the current store and update them. e.g.

     if(action.type === 'userAdded'){
        return [
          ...state,
           {
            id: 1, 
            name: action.payload.name
           }
        ]
     }
    

How Action, Store and Reducer works together ?

When a user dispatch an action like

store.dispatch({
  type: 'userAdded',
  payload: {
    id: 1,
    name: 'abc'
  }
})

then store will forward that dispatch action to the reducer (here we are not calling the reducer directly, the store is incharge of calling the reducer), the reducer computes the new state and returns it, next the store will set the state internally and then notifies the UI components about the state and these UI components will pull out the updated state and refresh themselves.

So why this architecture?

Because this architecture allows us to direct actions through a single entrance, we can keep track what action/events happend after what. And also helps us in debugging, logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment