Navigate
Search topics, hooks, and fundamentals
Replace push, splice, and direct assignment with immutable patterns. These are the exact patterns you will use with React state every day.
Use the spread operator to create a new array with the additional item:
// MUTATING (don't do this in React)
items.push(newItem);
// IMMUTABLE (correct for React state)
setItems([...items, newItem]); // add to end
setItems([newItem, ...items]); // add to startUse filter to create a new array without the target item:
// MUTATING (don't do this in React)
items.splice(index, 1);
// IMMUTABLE (correct for React state)
setItems(items.filter((_, i) => i !== index));
// or by ID:
setItems(items.filter(item => item.id !== targetId));Use map to create a new array where the target item is replaced with a new object:
// MUTATING (don't do this in React)
items[index].name = "New Name";
// IMMUTABLE (correct for React state)
setItems(items.map((item, i) =>
i === index ? { ...item, name: "New Name" } : item
));
// or by ID:
setItems(items.map(item =>
item.id === targetId ? { ...item, name: "New Name" } : item
));Practice all three operations on a shelf of pottery. Every action creates a new array — watch the reference change:
push(item)[...arr, item]splice(i, 1)filter((_, i) => i !== idx)arr[i].x = ymap(item => ...)