Could someone explain to me what are the reasons why Redux has two functions mapStateToProps and mapDispatchToProps that both add props to a container?
Definitions:
mapStateToProps is a utility which helps your component get updated state (which is updated by some other components)
mapDispatchToProps is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)
Why Redux team chose to break it into two mapping functions - i.e. why not have just one function mapToProps(state, dispatch, props) that do both?
- Is it just separation of concerns / easier to understand reason?
- Is it because of performance issues with re-binding in
mapDispatchToPropsthat creates new functions for every change? Having separate function for action creations bindings will help to avoid this extra job? Considering thatmapStateToPropsis called on every state change.
Example:
const increaseAction = { type: 'increase' }
class Counter extends Component {
render() {
const { value, onIncreaseClick } = this.props
return (
<div>
<span>{value}</span>
<button onClick={onIncreaseClick}>Increase</button>
</div>
)
}
}
function mapDispatchToProps(dispatch) {
return {
onIncreaseClick: () => dispatch(increaseAction)
}
}
See this Redux example on codesandbox
mapDispatchToPropsallocates functions for every action creator that is a very costly operation to redo when you have a lot of components. It looks like there are two different mechanisms that detect when redux needs to update the state and action creator bindings - therefore two different functions:mapStateToPropsandmapDispatchToProps. Is this the answer? - Andrey Prokhorov