Skip to content

Latest commit

 

History

History
94 lines (76 loc) · 2.41 KB

mapStateToProps-prefer-selectors.md

File metadata and controls

94 lines (76 loc) · 2.41 KB

Enforces that all mapStateToProps properties use selector functions. (react-redux/mapStateToProps-prefer-selectors)

Using selectors in mapStateToProps to pull data from the store or compute derived data allows you to uncouple your containers from the state architecture and more easily enable memoization. This rule will ensure that every prop utilizes a selector.

Rule details

The following pattern is considered incorrect:

const mapStateToProps = (state) => { x: state.property }
connect(function(state) { 
    return { 
        y: state.other.property
    }
}, null)(App)

The following patterns are considered correct:

const propertySelector = (state) => state.property
const mapStateToProps = (state) => { x: propertySelector(state) }
const getOtherProperty = (state) => state.other.property
connect(function(state) { 
    return { 
        y: getOtherProperty(state)
    }
}, null)(App)

Rule Options

...
"react-redux/mapStateToProps-prefer-selectors": [<enabled>, {
  "matching": <string>
  "validateParams": <boolean>
}]
...

matching

If provided, validates the name of the selector functions against the RegExp pattern provided.

    // .eslintrc
    {
        "react-redux/mapStateToProps-prefer-selectors": ["error", { matching: "^.*Selector$"}]
    }

    // container.js
    const mapStateToProps = (state) => {
        x: xSelector(state), // success
        y: selectY(state), // failure
    }
    // .eslintrc
    {
        "react-redux/mapStateToProps-prefer-selectors": ["error", { matching: "^get.*FromState$"}]
    }

    // container.js
    const mapStateToProps = (state) => {
        x: getXFromState(state), // success
        y: getY(state), // failure
    }

validateParams

Boolean to determine if the selectors use the correct params (<selectorFunction>(state, ownProps), where both params are optional). Defaults to true.

    // .eslintrc
    {
        "react-redux/mapStateToProps-prefer-selectors": ["error", { validateParams: true }]
    }

    // container.js
    const mapStateToProps = (state, ownProps) => {
        x: xSelector(state), // success
        y: ySelector(state, ownProps), // sucess
        z: zSelector(), // success
        a: aSelector(ownProps, state), // failure
        b: bSelector(state, someOtherValue) // failure
    }