Strangerliquid Strangerliquid - 20 days ago 8
React JSX Question

Bind react component to part of redux state

I have redux store that looks something like this:

{
user: {},
alerts: [],
reports: [],
sourses: []
}


For each one of this parts of state i have a bunch of React Components wrapped in a container wich connected via
react-redux
. And has
mapStateToProps
like this

(state) => {alerts: state.alerts}
(state, ownProps) => {alert: _.filter(state, {id: ownProps.curId})}


Problem that when i for example launch some action for Alerts like
CREATE_ALERT
or
EDIT_ALERT
and redux state updated, ALL REACT COMPONENTS WILL RESPOND TO THIS CHANGE even ones that works with different parts like
sources
or
reports
.

My question: how to "bind" certain components to certain parts of a tree. So each container component WILL UPDATE ONLY WHEN APROPRIATE PART OF REDUX STATE UPDATED and ignore other changes.

Expected behavior

Dispatch
CREATE_ALERT
-> Alert reducer -> Redux store update -> ONLY Alert container component re-rendering.

Answer

When you are changing state in redux the whole state is just a new object. And then your component is given by new object (new reference) and re-renderes itself.

To fix this behaviour you need to add some logic to compare if your component got props with different value (not reference).

The easiest and fastest way is to use React.PureComponent. You can also override shouldComponentUpdate function and handle changes by yourself.

Check also Immutable.js which helps you with intelligent way of changing references of props.