Redux is a predictable state container for JavaScript apps.
Redux also created by Facebook and it is a improvement from Flux. Redux is state management for any view library (mostly react)
When use Redux
Redux is design for complex UI, multiple view source or many interaction with server. If a simple UI, Redux is not necessary
Workflow
Example for Redux core
In index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Redux Core</title><!-- Use redux as UMD --><scriptsrc="https://unpkg.com/redux@latest/dist/redux.min.js"></script><!-- redux will be imported as Window.Redux --></head><body><divclass="app"></div><scriptsrc="./main.js"></script></body></html>
// UMD import
const{default:thunk}=ReduxThunk;const{applyMiddleware,createStore,combineReducers}=Redux;// init state
letinitUserState={name:'',age:0,};letinitPostState={content:'',};// reducer
constuserReducer=(prevState=initUserState,action)=>{switch(action.type){case'CHANGE_NAME':return{...prevState,name:action.payload};case'CHANGE_AGE':return{...prevState,age:action.payload};case'ERR':thrownewError('Err: '+action.error);default:break;}returnprevState;};constpostReducer=(prevState=initPostState,action)=>{switch(action.type){case'ADD_POST':return{...prevState,content:action.content};default:break;}returnprevState;};constreducers=combineReducers({user:userReducer,post:postReducer,});// store will looks like {user: ... , post: ...}
constlogger=({getState})=>(next)=>(action)=>{console.log({...action});console.log(getState());next(action);};// create store
conststore=createStore(reducers,applyMiddleware(thunk,logger));// init
store.subscribe(()=>{console.log('State: ',store.getState());});store.dispatch({type:'CHANGE_NAME',payload:'DVA89'});store.dispatch({type:'CHANGE_AGE',payload:30});store.dispatch({type:'CHANGE_AGE',payload:25});store.dispatch({type:'ADD_POST',content:'a test post'});