Enhancers
- It is the function to make higher-order function
- Could learn the use of recompose
Example
let foo = (....) => {...}
let enhancer = (aF, bF) => (p) => p(foo(aF, bF))
let container = enhancer(aF,bF)
let component = container(presenter) // <Presenter {...foo(aF, bF)}/>
For instance, connect
in redux
let operation = (ms, md, store, ownProps) => {
let p1 = ms(store.getState(), ownProps);
let p2 = md(store.dispatch, ownProps);
return {...p1, ...p2, ...ownProps}
}
let connect = (mapState, mapDispatch) => {
let ps = operation(mapState, mapDispatch, store)
return (component) => {
return component({...ps, ...component.props})
}
}
const mapStateToProps = (state, ownProps) => {...}
const mapDispatchToProps = (dispatch, ownProps) => {...}
let container = connect(mapStateToProps, mapDispatchToProps);
const presenter = (props) => (<SomeLayout/>);
let component = container(presenter)
connect
is an higher-order function provided by redux, in which stateless components are preferred due to a number of reasons. Some people also call thisenhancer
.connect
is designed to be reusable for cases thatstate
has to be injected to a stateless component in form ofprop
, oractioncreator
that also in form ofprop
has to be dispatched toreducer
,- and in fact, 95% of redux components are working in this way, thus it is highly reusable.
- With specific
mapSthToProps
is provided toconnect
, this enhancer will produce another higher-order function that ready to bind with presenter. This subsequent HOF is calledcontainer
.- container is reusable when
mapSthToProps
is shared - test on business logic should be asserted in this layer
- container is reusable when
- Once the stateless presenter is bound to
container
, the missingprops
are accomplished. Through the input-process-output routine implemented inside a functional component, UI would be rendered- this final component is a real component that returning UI
- we often call this higher-order components
- test on presentation should be asserted in this layer
Reference
- What is HOC?
- Give up OOP - inheritance
- In OOP world, we are writing in stateful way. We are happy with encapsulated lifecycle.
- In functional programming world, we are writing in stateless way. We should use HOF to enhance a component to HOC
- The HOF we use enhancer to produce is called containers
- https://dev.to/kayis/higher-order-what