Intro to Redux

Intro to Redux

State management library for JavaScript applications.

Hey Readers, In this blog I will introduce you to a state management library which is redux. Let's get started.

What is Redux?

Redux is a predictable state container for JavaScript apps.

  • Predictable state container: means we can store our entire application state in one place and know about that state.
  • For JavaScript apps: means we can use redux in any apps which use js library or frameworks. i.e React, Angular, Vue, etc...

Understand through cake-shop analogy

  • Suppose you want to eat a cake. You go to the cake shop. You make the order of your favorite cake. The shopkeeper takes out your ordered cake from inventory and you will get what you want.

  • Similarly, if we consider the above scenario in our app then Shop is our Store(where all our app states will stay). We as users make an order of cake, is our Action(Describes what has happened). And shopkeeper is out Reducer(Ties the store and actions together)

  • So based on the above scenario redux have mainly three core concepts.

  • Store
  • Action
  • Reducer

Three Principles of Redux

1st Principle:

"The global state of your application stored as an object inside a single store"

  • Tracking no. of cakes in an inventory.
{
    noOfCakes: 10
}

2nd Principle:

"The only way to change the state is to dispatch an action, an object that describes what happened"

  • To update the state of your app, you need to let redux know about it through an action.
  • Exp. You make an order of buying a cake that is an action in redux.
{
    type: "CAKE_ORDERED"
}

3rd Principle:

"To specify how the state tree is updated based on actions, you write pure reducers"

  • Shopkeeper is our reducer who will take out the cake from inventory and fulfill the order. so basically shopkeeper manages the no of cakes counted in inventory.
  • Exp. You make an order of buying a cake that is an action in redux.
const reducer = (state = initialState, action) = > {
             switch (action.type) {
                 case 'CAKE_ORDERED' : 
                   return { noOfCakes : state.noOfCakes + 1 }
                 default: return state
            }

Basic Workflow:

reduxworkflow.png

  • Our JS app will initially subscribe to the Redux Store so our app will have the latest status update from one place.
  • Whenever the User triggers any action from the UI, the Reducer function handles that action and updates the state according to the action.

Conclusion:

  • Redux has main three core concepts.
    • Store: CakeShop
    • Action: Make an order to buy a cake.
    • Reducer: Shopkeeper

That's it for this blog guys, Please give feedback in the comment box. Thanks for Reading.