Redux flow.

Abinash Panda
3 min readJan 24, 2020

Redux is A Predictable State Container for JS Apps or its works as a global storage for our web app.

ReduxJS setup:

You can download CDN from here.

Or

npm install reduxyarn add redux

Redux is an independent library that can be used with vanilla js, React, Vue, Angular and many more.

when our code gets bigger and bigger it’s hard to keep up with manageable code and we have to do stuff like prop drilling which we have to pass through components that don't need any state. In simple terms, redux solves a problem that is managing the state.

In the above diagram managing state in the different components is very hard so we create a global store like this. To distribute out-state across components.

import { createStore } from 'redux'import reducer from './reducer'const store = createStore(reducer)export default store;

In the above code, we are importing ‘createStore’ function which takes reducer as a parameter. Then we create a store and assign it into a variable called ‘store’ then we are exporting that variable.

Action Creators:

Before understanding the action creator we should know about the action. In redux action is an object which must contain a key called ‘type’ a reason action is an object because we can pass multiple values to the reducer.

So what is action creators? It’s just a function that returns an object and that object is an action.

import { INCREMENT } from './types'export function handleIncrement() {
return {type: INCREMENT }
}

Type:

we keep our type to a separate file and export it. we do this because it helps us to debug our code.

export const INCREMENT = "INCREMENT"

Reducer:

Reducer is a pure function that takes state and action and gives us a new state.

import { INCREMENT } = "INCREMENT"initialState = 0;
function reducer(state = initialState, action) {
if(action.type == INCREMENT) {
return ++state;
}
}

if we have multiple reducers we can marge with combine reducer

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})// This would produce the following state object{potato: {// ... potatoes, and other state managed by the potatoReducer ...},tomato: {// ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...}}

To dispatch an action to the reducer we use ‘dispatch(action creator())’ and we pass the action creator as a parameter. In this case, we are calling dispatch and inside we are calling action creator which gives us the action.

  • we can use ‘getState()’ to receive the state.
  • when state updates ‘subscribe()’ called.
  • we use another module called ‘react-redux’ tp combine our react app with redux.
  • The ‘provider’ is a component that provides the store with its child component.
  • connect is a function that receives the store from the provider it also gets the store when the store is updated.

--

--