State with Objects and Arrays
Never mutate state. Create a new object or array with spread, map and filter so React sees the change.
Example
const user = { name: "Ada", age: 20 };
const next = { ...user, age: 21 };
const list = [1, 2, 3];
const added = [...list, 4];
const removed = list.filter((x) => x !== 2);
const edited = list.map((x) => (x === 2 ? 20 : x));
console.log(user, next);
console.log(added, removed, edited);Result
{ name: 'Ada', age: 20 } { name: 'Ada', age: 21 }
[ 1, 2, 3, 4 ] [ 1, 3 ] [ 1, 20, 3 ]Exercise
Copy an object.
{ user, age: 21 }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.