UPD: I used React Dev Tools with Highlight Updates which seems to highlight each render() method call
I've written a simple React App which works the next way:
- It has a button and a list of numbers
- After clicking the button it adds a new number to the bottom of the list increased by 1 from the previous one
The problem is that React updates all list elements each time even when I use key property. I know that this problem can be solved by using PureComponents class or self-implemented shouldComponentUpdate()
Why React updates all list elements if they are not changed? I though that React uses special diffing algorithm for comparing elements and it should have worked, but now I see that it works not as I expected.
Could any body explain why React's diffing algorithm doesn't work in this case?
class App extends Component {
constructor(props) {
super(props);
this.state = {
numbers: []
}
this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick() {
const numbers = this.state.numbers;
const length = this.state.numbers.length ;
const newNumber = length > 0 ? numbers[length - 1] + 1 : 0;
this.setState({
numbers: [...numbers, newNumber]
})
}
render() {
return (
<div>
<button onClick={this.handleButtonClick}>Add</button>
<NumbersList numbers={this.state.numbers} />
</div>
);
}
}
class NumbersList extends Component {
render() {
return (
<ul>
{
this.props.numbers.map((number) => <NumberItem key={number} number={number} />)
}
</ul>
)
}
}
class NumberItem extends Component {
render() {
return (
<li>{this.props.number}</li>
)
}
}
<li>elements being added. Either I don't understand the question or I cannot reproduce this.<ul>and look through the process. You'll find that only the new<li>insertion happens. I guess React Dev Tools does something unexpected here.