React & Modern Frontend (445 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)
What are the preferred and non-preferred array operations for updating the state?
The below table represent preferred and non-preferred array operations for updating the component state.
| Action | Preferred | Non-preferred |
|---|---|---|
| Adding | concat, [...arr] | push, unshift |
| Removing | filter, slice | pop, shift, splice |
| Replacing | map | splice, arr[i] = someValue |
| sorting | copying to new array | reverse, sort |
If you use Immer library then you can able to use all array methods without any problem.
Practical Code Example
javascript
// Preferred Non-Mutating Array Operations:
// - Add: [...arr, item]
// - Remove: arr.filter(x => x.id !== targetId)
// - Modify: arr.map(x => x.id === targetId ? { ...x, active: true } : x)
// - Sort (ES2023): arr.toSorted()