Reputation: 158
I have react-redux component SideBar.js which is subscribing to slice of redux state. When the redux state changes, this component gets re-rendered unnecessarily even it does not subscribe to that changing state in redux. Since my state is nested, i do not want to do deep comparisons in shouldComponentUpdate() to avoid re-rendering ... how can i avoid extra re-rendering ?
const mapStateToProps = (state) => {
return {
guestLogin:{
status : state.guestLogin.status,
marketPlace:state.guestLogin.marketPlace,
newsFeed:state.guestLogin.newsFeed
},
accountLogin:{
showMemberPosts:state.accountLogin.showMemberPosts,
newsFeed: state.accountLogin.newsFeed,
marketPlace:state.accountLogin.marketPlace,
userInfo:state.accountLogin.userInfo
},
marketPlace:{
reset:state.marketPlace.reset,
disableFilters:state.marketPlace.disableFilters,
filters:state.marketPlace.filters,
}
};
};
const mapDispatchToProps = dispatch => {
return {
guestMarketPlaceClickHandler :()=>{dispatch(marketPlaceCLickHandlerDispatcher())},
guestNewsFeedClickHandler:()=>{dispatch(newsFeedClickHandlerDispatcher())},
memberMarketPlaceClickHandler:()=>{dispatch(marketPlaceCLickHandlerDispatcher())},
memberNewsFeedClickHandler:()=>{dispatch(newsFeedClickHandlerDispatcher())},
myPostsClickHandler:()=>{dispatch(myPostsClickHandlerDispatcher());},
dispatch:(action)=>{dispatch(action)}
}
};
export default connect(mapStateToProps,mapDispatchToProps)((SideBar));
Upvotes: 2
Views: 4039
Reputation: 5707
Connecting your component to redux makes it a PureComponent. That is, it will do a shallow comparison of the props to decide if it needs to re-render. By nesting your store values in mapStateToProps
you are guaranteeing that the shallow comparison will fail.
That is, guestLogin: {...}
creates a new object for the value of guestLogin every time.
You can either use reselect
or an equivalent solution to create selectors which return the same objects while the state doesn't change, or just make your mapStateToProps shallow, eg..
const mapStateToProps = (state) => {
return {
glStatus : state.guestLogin.status,
glMarketPlace:state.guestLogin.marketPlace,
glNewsFeed:state.guestLogin.newsFeed
alShowMemberPosts:state.accountLogin.showMemberPosts,
alNewsFeed: state.accountLogin.newsFeed,
alMarketPlace:state.accountLogin.marketPlace,
alUserInfo:state.accountLogin.userInfo
mpReset:state.marketPlace.reset,
mpDisableFilters:state.marketPlace.disableFilters,
mpFilters:state.marketPlace.filters,
};
};
Upvotes: 4