Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

Add Item Immutably

Immutable Arrayseasy

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 111: The Spread Operator (...)

State updates in React must not mutate. Implement `addItem(list, item)` returning a new array with `item` appended.

Sample tests

Input: addItem([1,2], 3)
Output: [1,2,3]
Input: addItem([], 1)
Output: [1]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • list.push(item) mutates the original array, so React keeps the same reference and may skip the re-render.
  • Returning the same array reference (even after pushing) defeats React change detection.

Learning resources

  • React: Updating Arrays in State
Approach & explanation (try first)

React decides whether to re-render by comparing references. push keeps the same array reference, so the change can be missed. Spreading into a new array with [...list, item] produces a new reference that includes the added item, which is what React expects from a state update.

Loading...
⌘/Ctrl + Enter

Run your code to see results.