
In frontend and application programming, local collection state is updated frequently when users add items. Interviewers ask this to assess whether you understand safe state updates, data structure choices, and how changes propagate through the UI.
Explain how you would manage the local state for a garment list when a new item is added.
Address these points:
The interviewer expects a clear explanation of the update pattern, the underlying data structure behavior, and common pitfalls. You should discuss both the straightforward array/list approach and when you might add supporting structures such as a hash map or set for validation or fast lookup.
A garment list is commonly stored as an in-memory array or list because the UI usually renders items in order. Adding a new item typically means creating a new list that contains the old items plus the new garment.
garments = [
{"id": 1, "name": "Shirt"},
{"id": 2, "name": "Jacket"}
]
Instead of mutating the existing list in place, create a new list when adding an item. This makes change detection more reliable, reduces side effects, and aligns with common UI state management patterns.
new_garments = garments + [new_item]
If IDs must be unique, a set or hash map can be used to check duplicates efficiently before insertion. This avoids scanning the full list every time when the collection becomes large.
if new_item["id"] in garment_ids:
raise ValueError("Duplicate garment id")
The new item may be appended, prepended, or inserted into sorted order depending on product requirements. The update logic should match the display rule, such as newest first or alphabetical by name.
new_garments = [new_item] + garments # newest first
Efficient rendering depends on stable item identifiers and predictable updates. Even when the list is recreated immutably, stable IDs help the UI update only the affected elements rather than rerendering everything unnecessarily.
key = garment["id"]