Front End Workshops
Redux Advanced
Enrique Oriol
eoriol@naradarobotics.com
Alex Adrià
aadria@visual-engin.com
Previously in ReactJS...
ReactJS Basics
1. Decompose UI into reusable components which
render to virtual DOM
2. ReactJS will sync VDOM to real browser DOM
3. JSX format
4. Can render on client and server
What is a HOC?
● It is a JavaScript function which is used for adding
additional functionality to existing component
● A takes an existing component and returns another
component that wraps it.
● If the HOC data changes, It will re-run again and update
the resulting component.
● It usually contains reusable common behaviours
resulting in simpler and better structured components.
● A component can be wrapped several times by multiple
wrappers.
Redux life-cycle with middlewares
Middleware
React Action Creator
Action
Reducers
State
Calls Returns
Sent to
Forwards
action to
Creates new
Sent to Middleware receives
the action
and can log
stop and modify it
Middleware stack example 1
Middleware # 1
I don’t care about this action, I’ll send it
to the NEXT middleware
Action Creator Action
Reducers
next
Middleware # 2
I will log this action, and move it
forward
Middleware # 3
I don’t care about this action, I’ll send it
to the NEXT middleware
next
console.log()
Middleware structure
● It is a function that receives the store
● It MUST return a function with arg “next”
● That returns a function with arg “action”
○ Where we do our stuff
○ And return
■ next(action)
■ state.dispatch(action)
export default store => next => action => {
//do something
//next(action); or state.dispatch(action);
}
}
Middleware structure ES6
export default ({dispatch}) => next => action => {
//our stuff
}
}
src/middleware/myMiddleware.js
In case we don’t need the store
Simplest example - logger
Middleware
REACT IncreaseCounter() INC_ACTION
ReducersSTATE
- counter
Forwards
action to
Component
counter
+
- DecreaseCounter()
DEC_ACTION
Update
state
counter
logger
Using our middleware
import {createStore, applyMiddleware } from 'redux';
import reducers from './reducers';
import MyMid from './middlewares/my-middleware';
const createStoreWithMiddleware = applyMiddleware(myMid)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
src/index.js
Modify action middleware workflow
Middleware that modifies specific
action
Is it the action that I want?
Action Creator Action
no yes
Send action
forwards
Next middleware
Do some
stuff
Create new action
with the results Action
Middleware
stack
next(action)
store.dispatch(newAction)