Abinav Seelan
UI Engineer @Flipkart β’ Ex @hashnode & @SaltsideTech β’ Javascript Junkie & Pokemon League Champion from India. https://abinavseelan.com π
Redux
@abinavseelan
blog.campvanilla.com
Maintaining application state is hard.
Payment Gateway
Application
Application
Cart
Payment Gateway
Application
Cart
Payment Gateway
Product Page
Search
Application
Cart
Payment Gateway
Product Page
Search
π’
You no longer understand what happens in your app as you have lost control over the when, why, and how of its state.
- The Redux Docs
Redux helps simplify application state.
Application
Cart
Payment Gateway
Product Page
Search
Application
Cart
Payment Gateway
Product Page
Search
Store
Payment Gateway
Store
Payment Gateway
Store
Action
Reducer
Action
An object describing what happened.
Reducer
A pure function that defines how the state changes for a given action.
Action
{
type: 'ADD_ITEM_TO_CART',
data: {
id: 7337,
name: 'OnePlus 6',
price: 34999
}
}
Reducer
const initialState = {
items: [],
amount: 0,
};
function(state = initialState, action) {
let newState;
if (action.type === 'ADD_ITEM_TO_CART') {
newState = {
...state,
items: [...state.items, action.data],
amount: state.amount + action.data.amount,
};
} else {
newState = state;
}
return newState;
}
Three Principles
Single source of truth
The state is read-only
Changes are made using pure functions
Redux helps make application state predictable.
Redux: The Library
Creating a store
import { createStore } from 'redux';
function reducer(state = {}, action) {
...
}
const store = createStore(reducer);
The
store object
const store = createStore(reducer);
store.getState();
/*
This method returns the state of
the store.
*/
store.dispatch();
/*
This method allows you to dispatch
`actions` to the store. Takes an
`action` as a parameter.
*/
store.subscribe();
/*
This method allows you to add
listeners that trigger on store
updates. Takes a callback as a
parameter.
*/
Demo
Action
Creators
function addItem(item) {
return {
type: 'ADD_ITEM_TO_CART',
data: item,
}
}
Multiple
reducers
import { combineReducers } from 'redux';
function cartReducer(state = {}, action) {
...
}
function productReducer(state = {}, action) {
...
}
const rootReducer = combineReducer({
cart: cartReducer,
product: productReducer,
});
/*
This would generate the following state object
{
cart: {
// all state values managed by cartReducer
},
product: {
// all state values managed by productReducer
}
}
*/
const store = createStore(rootReducer);
A sort-of real world demo
Developer experience
Debugging
Root cause identification
Write tests
Time travelΒ
Bonus!
Track user sessions
Optimistic updates
Share actions over the network - collaboration
That's all folks! π
By Abinav Seelan
Talk given at Flipkart's UI Bootcamp, 2018
UI Engineer @Flipkart β’ Ex @hashnode & @SaltsideTech β’ Javascript Junkie & Pokemon League Champion from India. https://abinavseelan.com π