HOC & Redux connect()

1. HOC

Frontend people are familiar with HOC(High Order Component) or HOF(Higher Order Function). It can be thought as as an enhanced version of the original Component. Recently, I read an article about mixin pattern drawbacks in React (NOTE: mixing pattern now is obsolete, and HOC are recommended by Facebook React Team).

Personally, I love the way React Doc delivers its concepts, which is very natural and follow the way of regular thought process. Do have a look at this part: Higher-Order Components Explained. Thanks for the efforts from React Team.

2. connect() from Redux

In React-Redux, we see connect()() a lot, actually it is a HOC. Let’s write one! Also note this.context actually passed from <Provider> created by Redux. And it use context in React to pass it to its children.

[NOTE] The return of connect() is: a wrapper function that takes your component and returns a wrapper component with the additional props it injects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
export const connect = (mapStateToProps, mapDispatchToProps) => (WrappedComponent) => {
class Connect extends Component {
static contextTypes = {
store: PropTypes.object
}

constructor () {
super()
this.state = {
allProps: {}
}
}

componentWillMount () {
const { store } = this.context
this._updateProps()
store.subscribe(() => this._updateProps())
}

_updateProps () {
const { store } = this.context
let stateProps = mapStateToProps ? mapStateToProps(store.getState(), this.props): {}
let dispatchProps = mapDispatchToProps? mapDispatchToProps(store.dispatch, this.props) : {}
this.setState({
allProps: {
...stateProps,
...dispatchProps,
...this.props
}
})
}

render () {
return <WrappedComponent {...this.state.allProps} />
}
}
return Connect
}

3. Reference

  1. Use HOCs For Cross-Cutting Concerns

  2. Mixins Considered Harmful

  3. Mixin to HOC to Hook