Hi, I am fairly new to Redux, and I have been recently introduced to the react-redux package, that comes with two useful imports which let redux and react interact with each other. The two imports are the Provider and the Connect. While I can certainly see it is easier to use the react-redux provider class instead of creating your own class, I am a bit confused as to why the connect method is preferable over context/proptypes . For instance, consider the following example of a simple counter application (which allows you to dispatch an action to increment or decrement a counter).
PropTypes and Connect Method:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Counter extends Component {
render() {
let store = this.context.store;
return ( <div className="Counter">
<button onClick={() => store.dispatch({type: 'increment'})}>+</button>
<button onClick={() => store.dispatch({type: 'decrement'})}>-</button>
</div>);
}
}
Counter.contextTypes = { store: PropTypes.object};
export default Counter;
React-Redux Connect Method:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Counter extends Component {
render() {
this.dispatch = this.props.dispatch;
return (
<div className="Counter">
<button onClick={() => this.dispatch({type: 'INCREMENT'})}>+</button>
<button onClick={() => this.dispatch({type: 'DECREMENT'})}>-</button>
</div>);
}
}
const dispatch = (state) => {
return { state,}
}
export default connect(dispatch)(Counter);
In fact, I think the first example using context and proptypes is even more readable than the second example using connect.
So can anyone tell me the benefit of using connect from react-redux?
Christian Genco
gen.co
Stability, for one.
The React docs on Context say:
If you want your application to be stable, don’t use context. It is an experimental API and it is likely to break in future releases of React.In fact, the new version of context was proposed in December of 2017 and is on its way.
Presumably,
react-reduxwill be automatically updated for you to use this new API. If you implemented your own context/proptypes passing of the reduxstore, you'd have to manually change your code to the new syntax.