Reputation: 3487
After reading a barrage of articles on React, Redux and memoization, I'll like to ask a question... Can I get away with this use case:
Assume I have a redux store with the following data
// reduxStore
module.exports = {
randomData: [
{ name: 'John', age: 30 },
{ name: 'Peter', age: 25 },
{ name: 'Brenda', age: 15 }
];
};
Now, in my component, I will like to retrieve the average age. I go about it like so:
import React from 'react';
import { connect } from 'react-redux';
export function TestComponent(props) {
return <p>The sum of ages is: {props.ageSum}</p>;
}
const mapStateToProps = state => ({
ageSum: state.randomData.map(datum => datum.age).reduce((acc, curr) => acc + curr)
});
const mapDispatchToProps = {};
export default connect(mapStateToProps, mapDispatchToProps)(TestComponent);
I'm under the impression that this works the same as the examples given with reselect
and the other libraries recommended by React.
Can someone please explain, if and why this example is not wise when it comes to optimization...
Upvotes: 2
Views: 3774
Reputation: 67459
That example would work, but it would not be best for performance.
In most cases, calling map()
in your mapStateToProps
function will result in a new array reference being returned. Different references means the results are not shallow equal to last time, so your component will re-render. Memoization can help ensure that you only generate new references (like someArray.map()
) when the input values have actually changed.
In your case, the map
result is immediately being fed into a reduce()
, and used to calculate a sum. Assuming the calculated sum is the same each time, your component will not re-render, so it's not as much of a concern.
However, it's likely that state.randomData
has not changed most of the time, in which case the map().reduce()
is doing unnecessary work. Memoization would also help avoid that.
See the React-Redux docs on writing mapState
functions and my post Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance for more details on this.
Upvotes: 2