React / Redux: mapStateToProps() is called many times

Viewed 1446

I'm writing simple app using React / Redux. I notice that function mapStateToProps() is called many times. Here`s code:

class Employees extends React.Component {
    componentDidMount() {
        this.props.fetchEmployees();
    }
}

let mapStateToProps = function mapStateToProps(state) {
    console.log("foo");
    return {...};
};

let mapDispatch = (dispatch) => {
    return {
        fetchEmployees: bindActionCreators(fetchEmployees, dispatch)
    };
};

export default connect(mapStateToProps, mapDispatch)(Employees);

And what I get in console:

enter image description here

Is it normal or I'm doing something wrong?

1 Answers

Anytime there is a change in state of redux or the parent component of your container re-renders the mapStateToProps is being called. This however won't cause your component's render to call again provided the data returned by mapStateToProps and the props that it receives hasn't changed.

If you have some computation that you do in mapStateToProps that returns a value, make sure you use a memoized function to do that computation or reselect to write memoized selectors so that the same value is returned for the same computation even if mapStateToProps is called multiple times

Related