Performance: Immutable patterns for updates
This affects how efficiently the UI updates by minimizing unnecessary DOM changes and re-renders.
let items = [1, 2, 3]; function addItem(newItem) { items = [...items, newItem]; }
let items = [1, 2, 3]; function addItem(newItem) { items.push(newItem); items = items; // reassign to trigger update }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Mutable update with reassignment | Full list re-render | Multiple reflows | High paint cost | [X] Bad |
| Immutable update with new array | Partial DOM update | Single reflow | Low paint cost | [OK] Good |
4 to numbers?let todos = [
{ id: 1, text: 'Buy milk', done: false },
{ id: 2, text: 'Walk dog', done: false }
];
// Update to mark todo with id 2 as done
todos = todos.map(todo => todo.id === 2 ? { ...todo, done: true } : todo);todos after this update?let user = { name: 'Alice', age: 25 };
// Update age
user.age = 26;
user = user;let profile = {
name: 'Bob',
address: { city: 'NY', zip: '10001' }
};
// You want to update zip to '10002' immutably. Which is correct?Pass the test and this pattern moves unknown