Lesson 24 of 3080%
(Progress persistence is disabled until Phase 9)
React
Beginner
Working with Arrays and Objects
The golden rule of immutable state updates.
When your state is an array or an object, you must treat it as immutable.
You cannot use push(), pop(), or modify object properties directly, because React won’t detect the change.
Objects
Use the Spread Syntax (...) to copy the old object and overwrite specific fields.
const [user, setUser] = React.useState({ name: "Alice", age: 20 });
// Wrong:
user.age = 21; setUser(user);
// Right:
setUser({ ...user, age: 21 });
Arrays
Use Spread Syntax, filter(), or map() to create new arrays.
const [list, setList] = React.useState([1, 2, 3]);
// Add to end
setList([...list, 4]);
// Remove item (e.g. remove number 2)
setList(list.filter(item => item !== 2));
Try It Yourself