State with Objects and Arrays
When state holds objects or arrays, you need to be careful to update them correctly. React requires immutable updates to detect changes.
The Immutability Rule
React uses reference comparison to detect changes. You must create new objects/arrays, not mutate existing ones:
Loading React playground...
Updating Objects
Always spread the existing object and override specific properties:
Loading React playground...
Updating Arrays
Arrays also need immutable updates using methods that return new arrays:
Loading React playground...
Common Patterns
Loading React playground...
Exercise: Update Nested Object
Loading exercise...
Exercise: Array CRUD Operations
Loading exercise...
Exercise: Complex State Update
Loading exercise...
Key Takeaways
- Never mutate - Always create new objects/arrays
- Spread operator -
{...obj}and[...arr]create copies - Nested updates - Spread at each level of nesting
- Array methods - Use map, filter, spread for updates
- Reference check - React needs new references to re-render

