Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mapStateToProps and mapDispatchToProps are not just one function in Redux?

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 mapDispatchToProps that creates new functions for every change? Having separate function for action creations bindings will help to avoid this extra job? Considering that mapStateToProps is 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

like image 219
Andrey Prokhorov Avatar asked Nov 26 '17 21:11

Andrey Prokhorov


1 Answers

@Andrey Prokhorov is right, and it's funny you asked. I found myself in the bowels of github issues earlier today and found this issue (Add state as the third parameter to mapDispatchToProps). While the title doesn't seem to relate, if you dig through the comments, gaearon (the creator of react-redux) explains:

Please take a look at #1. This option has been considered and rejected. Yes, it's very bad for performance to re-bind action creator on every dispatch, which is what will happen if we let people access the state in the same place they bind action creators. Technically they can still do it now with mergeProps but it's hidden well enough that people who aren't experienced with Redux don't discover it by mistake.

I also linked to the very first issue that gaearon linked to for react-redux where it was discussed (it was literally issue #1 on github for react-redux). I'm sure they COULD change it to the way you describe, but I think gaearon's comment sums it up:

The goal of this library is to encourage performant patterns because otherwise people will say “Redux is slow!” even if the cause is their suboptimal function binding code. We don’t want this to happen, so we’d rather make certain unperformant cases harder to implement.

like image 178
Jack Avatar answered Oct 23 '22 12:10

Jack