Skip to main content
InterviewHubPRO
Section Overview
Q258

Question 258 of 407

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

63%
React Core & Hooks (407 Qs)•Part 8: Advanced React Patterns, Portals & Performance (152 - 261)

What are the preferred and non-preferred array operations for updating the state?

junior LevelCode ExampleFormsPerformanceData Structures

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()