There are several questions and answers related props vs state, but I'm still confused.
In short, documentation and answers agree that props should be immutable and state mutable.
But the whole idea of mapStateToProps
is to be able to update the props when the state changes; and subsequently trigger a re-render? So why does does this crucial method exists?
I need to display a modal notification popup. The notification should be displayed once the data is added to the state, and only if there exists such a notification.
function mapStateToProps(state) {
return {
notifications: getNotifications(state),
};
}
The problem:
According to best practice I should use access the state in my render(), since it may change at any time. I.e. this.state.notifications
. But mapStateToProps
never updates the component's state. So, to get the desired effect I need to use this.props.notifications
-the anti pattern.
render() {
return (
{this.props.notifications.length > 0 && (
<Notification
isVisible={this.props.notifications.length > 0}
title={this.props.notifications[0].title}
/>
)}
<SomeOtherAlwaysVisibleViews />
);
The above is working. I don't see why I should trigger on prop changes and use setState instead, just to use state instead of props in render()?