React JS Course
Redux is a tool to help you manage global state. Redux is built around the concept of actions and reducers.
The advantages of Redux are
- Centralizes application's state
- Makes data flow transparent and predictable
Redux Architecture
We need to follow the below steps in building a redux app.
- Design the store
- Define the actions
- Create a reducer
- Setup the store
- Action
Actions are just objects with a type and a payload(optional). Each action has a case correlated in the reducer file. Actions only tell what to do, but they don't tell how to do.
For example,
return { type: ADD_EMPLOYEE, payload: employee }
Action Creator
Pure function which creates an action
For example,
const addEmployee = employee => { return { type: ADD_EMPLOYEE, payload: employee } }
This is Reusable, Portable and Easy To Test.
- Reducer
Reducers are the functions that take the current state and an action as arguments, and return a new state result.
For example,
const intialState = { employees: [], } const reducer = (state = intialState, action) => { switch (action.type) { case FETCH_EMPLOYEES: return { employees: action.payload, } case ADD_EMPLOYEE: return { ...state, employees: [...state.employees, action.payload], } case DELETE_EMPLOYEE: return { employees: [ ...state.employees.filter(employee => employee !== action.payload) ] } case UPDATE_EMPLOYEE: return { employees: [ ...state.employees.map(emp => emp.emailId === action.payload.emailId ? { ...state.employees, ...action.payload } : emp) ] } default: return state } }
- Store
The Redux store brings together the state, actions and reducers that make up your app.
It's important to note that you will only have a single store in a Redux application.
Every Redux store has a single root reducer function.
For example,
const rootReducer = combineReducers({ employee: employeeReducer }) import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; const store = createStore(rootReducer, applyMiddleware(thunk))
In redux, you need to dispatch your action. You can perform logic and asynchronous calls here. After your action is dispatched, redux will look for a case in reducer that matches the type. The reduceris where state update happen. Combine all this together and you will have powerful global state management.

Redux Principles
- Single source of Truth
The global state of your application is stored as an object inside a single store.
- State is Read-Only
The only way to change the state is to dispatch an action.
-
Immutability, One-way data flow, Predictability of outcome
-
Changes are Made with Pure Reducer Functions