Reputation: 2036
I am working on a React/Redux application. Let's say I have a component that receives two props from it's container:
// NewsFeedItem.js
class NewsFeedItem extends React.Component {
render() {
const user = this.props.user;
const item = this.props.item;
return <p>{user.name} - {item.date}</p>;
}
}
const mapStateToProps = (state) => ({
user: state.user,
item: state.user.items[0],
});
export default connect(mapStateToProps)(NewsFeedItem);
How can I make sure this Component doesn't update if I make a change to the 2nd or 3rd item in the items list?
Upvotes: 1
Views: 158
Reputation: 67627
Pasting in my answer from the associated Redux issue for completeness:
First, there's nothing wrong with a React component re-rendering - that's how React works in the first place. If a component re-renders with the same data and produces the same render output, then React just doesn't update the DOM. Now, sure, that's considered a "wasted" re-render that probably could have been avoided, but it's only a problem if you're trying to seriously optimize performance.
Second: yes, if you're correctly immutably updating your state, then an update to state.user.items[3]
should result in new references for items
, user
, and state
, and passing user
as a prop to the component like that would cause it to re-render. However, in your specific example, that component is only using user.name
. so there's no reason to pass the entire user
object as a prop - try passing just name : state.user.name
instead.
Third, you could split up the storage of the user attributes and their associated items into separate parts of the state, so that an update to an item doesn't cause an update to the associated user object. See the Normalizing State Shape page in the Redux docs as an example.
Finally, you could always implement a custom shouldComponentUpdate
in your component, and do an additional check there to see if the component should skip re-rendering.
Upvotes: 1