Create a gist now

Instantly share code, notes, and snippets.

Embed
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

This comment has been minimized.

Show comment
Hide comment
@aweary

aweary May 17, 2016

Alright, now React next! ๐Ÿ˜„

aweary commented May 17, 2016

Alright, now React next! ๐Ÿ˜„

@philipstanislaus

This comment has been minimized.

Show comment
Hide comment
@philipstanislaus

philipstanislaus Oct 4, 2016

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

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

@therewillbecode

This comment has been minimized.

Show comment
Hide comment
@therewillbecode

therewillbecode Dec 12, 2016

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

therewillbecode commented Dec 12, 2016

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

This comment has been minimized.

Show comment
Hide comment
@eqyiel

eqyiel 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.

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.

@nonnontrivial

This comment has been minimized.

Show comment
Hide comment
@nonnontrivial

nonnontrivial Feb 11, 2017

Super clear and helpful. Thanks :)

Super clear and helpful. Thanks :)

@Dianna

This comment has been minimized.

Show comment
Hide comment
@Dianna

Dianna Apr 22, 2017

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

Dianna commented Apr 22, 2017

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

@iroy2000

This comment has been minimized.

Show comment
Hide comment
@iroy2000

iroy2000 Jun 7, 2017

Thanks a lot, it makes understanding the redux implementation much easier ๐Ÿ‘

iroy2000 commented Jun 7, 2017

Thanks a lot, it makes understanding the redux implementation much easier ๐Ÿ‘

@andersonferrari

This comment has been minimized.

Show comment
Hide comment
@andersonferrari

andersonferrari Jul 27, 2017

great explanation!!! thanks!!!

great explanation!!! thanks!!!

@esafirm

This comment has been minimized.

Show comment
Hide comment
@esafirm

esafirm Aug 18, 2017

Wow this is great ๐Ÿ‘

esafirm commented Aug 18, 2017

Wow this is great ๐Ÿ‘

@gulshanzealous

This comment has been minimized.

Show comment
Hide comment
@gulshanzealous

gulshanzealous Sep 6, 2017

Aha moment ! Concise and powerful : terms we hardly associate together with libraries.

Aha moment ! Concise and powerful : terms we hardly associate together with libraries.

@karltaylor

This comment has been minimized.

Show comment
Hide comment

๐Ÿ‘

@devvtms

This comment has been minimized.

Show comment
Hide comment
@devvtms

devvtms Sep 20, 2017

here is my decorator to simplify things:

import React from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as actions from "./actions";
const decorator = ComponentToDecorate => {
  class ComponentDecorated extends React.Component {
    render() {
      const { authState, authActions, ...rest } = this.props;
      return (
        <ComponentToDecorate auth={{ state: authState, actions: authActions }}
          {...rest}
        />
      );
    }
  }

  return connect(
    state => ({
      authState: state.services.auth.authentication
    }),
    dispatch => ({
      authActions: bindActionCreators(actions, dispatch)
    })
  )(ComponentDecorated);
};

export default decorator;

i use it in some complicated components. is there is anything wrong with this?

devvtms commented Sep 20, 2017

here is my decorator to simplify things:

import React from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as actions from "./actions";
const decorator = ComponentToDecorate => {
  class ComponentDecorated extends React.Component {
    render() {
      const { authState, authActions, ...rest } = this.props;
      return (
        <ComponentToDecorate auth={{ state: authState, actions: authActions }}
          {...rest}
        />
      );
    }
  }

  return connect(
    state => ({
      authState: state.services.auth.authentication
    }),
    dispatch => ({
      authActions: bindActionCreators(actions, dispatch)
    })
  )(ComponentDecorated);
};

export default decorator;

i use it in some complicated components. is there is anything wrong with this?

@kinotto

This comment has been minimized.

Show comment
Hide comment
@kinotto

kinotto Oct 11, 2017

fantastic! clear and concise, thanks @gaearon

kinotto commented Oct 11, 2017

fantastic! clear and concise, thanks @gaearon

@Nerhbest

This comment has been minimized.

Show comment
Hide comment
@Nerhbest

Nerhbest Oct 31, 2017

Thank you,very clear explanation,like you methods to educate.
Especially , you approach when you explain how things work under the hood!

Thank you,very clear explanation,like you methods to educate.
Especially , you approach when you explain how things work under the hood!

@vitali-zaneuski

This comment has been minimized.

Show comment
Hide comment
@vitali-zaneuski

vitali-zaneuski May 5, 2018

Good and brief explanation

Good and brief explanation

@Bosn

This comment has been minimized.

Show comment
Hide comment
@Bosn

Bosn May 18, 2018

Fantastic work!

Bosn commented May 18, 2018

Fantastic work!

@ashinzekene

This comment has been minimized.

Show comment
Hide comment
@ashinzekene

ashinzekene Jun 9, 2018

Can this be used in prod?

Can this be used in prod?

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