You can do it by using any state management library, so that your Parent
doesn’t keep track of this.state.list
=> your List
only re-renders when new Item
is added. And the individual Item
will re-render when they are updated.
Lets say you use redux
.
Your code will become something like this:
// Parent.js
class Parent extends React.Component {
render() {
return <List />;
}
}
// List.js
class List extends React.Component {
render() {
var list = this.props.list.map(item => {
return <Item key={item.key} uniqueKey={item.key} />;
});
return <div>{list}</div>;
}
}
const mapStateToProps = (state) => ({
list: getList(state)
});
export default connect(mapStateToProps)(List);
// Item.js
class Item extends React.Component {
shouldComponentUpdate() {
}
render() {
}
}
const mapStateToProps = (state, ownProps) => ({
item: getItemByKey(ownProps.uniqueKey)
});
export default connect(mapStateToProps)(Item);
Of course, you have to implement the reducer and the two selectors getList
and getItemByKey
.
With this, you List
re-render will be trigger if new elements added, or if you change item.key
(which you shouldn’t)