React Redux -- can I make mapStateToProps only take in part of the state?

That is actually something of a complicated topic. Because Redux is a single global store, the idea of a completely encapsulated, fully reusable plug-and-play set of logic does become rather difficult. In particular, while the reducer logic can be fairly generic and ignorant of where it lives, the selector functions need to know where in the tree to find that data.

The specific answer to your question is "no, mapState is always given the complete state tree".

I do have links to a number of relevant resources, which may possibly help with your situation:

  • There's several existing libraries that try to implement "per-component state in Redux". I have a list of them in my Redux addons catalog, in the Component State category.
  • A group of devs have been discussing and prototyping various approaches to the "reusable logic module in Redux" concept. Their work is at https://github.com/slorber/scalable-frontend-with-elm-or-redux .
  • Randy Coulman recently posted a three-part blog series related to state encapsulation and modularity in Redux. He didn't come up with definitive answers, but the posts are worth reading: Encapsulating the Redux State Tree, Redux Reducer Asymmetry, and Modular Reducers and Selectors.

Although mapStateToProps (the first function you pass to connect) gets passed the whole store as you said, its job is to map specific parts of the state to the component. So only what is returned from mapStateToProps will be mapped as a prop to your component.

So lets say your state looks like this:

{
    account: {
        username: "Jane Doe",
        email: "[email protected]",
        password: "12345",
        ....
    },
    someOtherStuff: {
        foo: 'bar',
        foo2: 'bar2'
    },
    yetMoreStuff: {
        usuless: true,
        notNeeded: true
    }
}

and your component needs everything from account and foo from someOtherStuff then your mapStateToProps would look like this:

const mapStateToProps = ({ account, someOtherStuff }) => ({
    account,
    foo: { someOtherStuff }
});
export default connect(mapStateToProps)(ComponentName)

then your component will have the prop account and foo mapped from your redux state.


Redux only has a single store as you know, so all it knows to do is pass the entire store to your mapStateToProps function. However using object destructuring, you can specify which properties in the store you want and ignore the rest. Something like 'function mapStateToProps({prop1, prop2})' would only capture those two properties in the store and ignore the rest. Your function is still receiving the entire store, but you're indicating that only these props interest you.

In my example, 'prop1' and 'prop2' would be the names you assigned your reducers during the call to 'combineReducers'.