Strangerliquid Strangerliquid - 1 year ago 86
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
. And has
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
and redux state updated, ALL REACT COMPONENTS WILL RESPOND TO THIS CHANGE even ones that works with different parts like

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download