InterviewHubPRO
Section Overview
Q258

Question 258 of 445

Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

58%
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.

ActionPreferredNon-preferred
Addingconcat, [...arr]push, unshift
Removingfilter, slicepop, shift, splice
Replacingmapsplice, arr[i] = someValue
sortingcopying to new arrayreverse, 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()