Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
connect.js explained
// connect() is a function that injects Redux-related props into your component.
// You can inject data and callbacks that change that data by dispatching actions.
function connect(mapStateToProps, mapDispatchToProps) {
// It lets us inject component as the last step so people can use it as a decorator.
// Generally you don't need to worry about it.
return function (WrappedComponent) {
// It returns a component
return class extends React.Component {
render() {
return (
// that renders your component
<WrappedComponent
{/* with its props */}
{...this.props}
{/* and additional props calculated from Redux store */}
{...mapStateToProps(store.getState(), this.props)}
{...mapDispatchToProps(store.dispatch, this.props)}
/>
)
}
componentDidMount() {
// it remembers to subscribe to the store so it doesn't miss updates
this.unsubscribe = store.subscribe(this.handleChange.bind(this))
}
componentWillUnmount() {
// and unsubscribe later
this.unsubscribe()
}
handleChange() {
// and whenever the store state changes, it re-renders.
this.forceUpdate()
}
}
}
}
// This is not the real implementation but a mental model.
// It skips the question of where we get the "store" from (answer: <Provider> puts it in React context)
// and it skips any performance optimizations (real connect() makes sure we don't re-render in vain).
// The purpose of connect() is that you don't have to think about
// subscribing to the store or perf optimizations yourself, and
// instead you can specify how to get props based on Redux store state:
const ConnectedCounter = connect(
// Given Redux state, return props
state => ({
value: state.counter,
}),
// Given Redux dispatch, return callback props
dispatch => ({
onIncrement() {
dispatch({ type: 'INCREMENT' })
}
})
)(Counter)

aweary commented May 17, 2016

Alright, now React next! 😄

Thanks for the explanation, @gaearon! Might it be possible that you talk a bit about the performance optimizations in the connect function? Thanks!

therewillbecode commented Dec 12, 2016 edited

Really useful example. Thanks so much.

Why is the unsubscribe method of the decorated component being called here in componentDidMount?
I am confused as the comment says:

it remembers to subscribe to the store so it doesn't miss updates

eqyiel commented Jan 6, 2017

@therewillbecode see http://redux.js.org/docs/api/Store.html#subscribe

To unsubscribe the change listener, invoke the function returned by subscribe.

Super clear and helpful. Thanks :)

Dianna commented Apr 22, 2017

Thank you! Pseudo-implementations help my mental model tons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment