kibowki
kibowki

Reputation: 4366

How is Redux passing state to mapStateToProps?

I'm trying to understand how React and Redux work, and I was looking at FuelSavingsPage.js from this example project. I get where actions comes from in mapDispatchToProps, but I don't understand how state is being passed to mapStateToProps or how dispatch is being passed to mapDispatchToProps. How is this happening?

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/fuelSavingsActions';
import FuelSavingsForm from '../components/FuelSavingsForm';

export const FuelSavingsPage = (props) => {
  return (
    <FuelSavingsForm
      saveFuelSavings={props.actions.saveFuelSavings}
      calculateFuelSavings={props.actions.calculateFuelSavings}
      fuelSavings={props.fuelSavings}
    />
  );
};

FuelSavingsPage.propTypes = {
  actions: PropTypes.object.isRequired,
  fuelSavings: PropTypes.object.isRequired
};

function mapStateToProps(state) {
  return {
    fuelSavings: state.fuelSavings
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(FuelSavingsPage);

Upvotes: 5

Views: 3303

Answers (2)

semanser
semanser

Reputation: 2348

All magic in connect() function. This function calls mapStateToProps and passes state as a prop. The same thing happens with mapDispatchToProps and the dispatch method. You can imagine this with the following pseudo-code:

function connect(mapStateToProps, mapDispatchToProps) {
    mapStateToProps(store.getState()) // just simple callback
    mapDispatchToProps(store.dispatch) // the same
}

Upvotes: 8

markerikson
markerikson

Reputation: 67459

The React-Redux connect function generates a wrapper component that subscribes to the store. That wrapper component calls store.getState() after each dispatched action, calls the supplied mapStateToProps function with the current store state, and if necessary, calls mapDispatchToProps with the store's dispatch function.

Dan wrote a simplified version of connect a while back to illustrate the general approach it uses. See https://gist.github.com/gaearon/1d19088790e70ac32ea636c025ba424e .

Upvotes: 6

Related Questions