useArray Hook
Build a useArray(initial) custom hook that returns { items, push, removeAt, clear } and wire it into a small list manager UI: an input + Add button to push, per-row Remove buttons, a Clear button, and a live count.
Custom hooks are the idiomatic way to package reusable stateful logic in React. A common pattern is wrapping array state behind a small, ergonomic API so components never reach for raw setState array spreads.
In this exercise you implement useArray(initial), a hook that owns an array of strings and exposes helpers to mutate it:
items— the current array.push(value)— appendsvalueto the end of the array.removeAt(index)— removes the element at the given index.clear()— empties the array.
All updates must be immutable (return new arrays rather than mutating the existing one) and the helpers should be stable so they behave predictably across renders.
Then wire the hook into the App UI:
- A text input with placeholder
"New item"and an Add button. Clicking Add pushes the input's current (trimmed, non-empty) value into the array and clears the input. Empty/whitespace-only input is ignored. - A list rendering each item, where every row has a Remove button that removes exactly that item via
removeAt. - A Clear button that empties the list.
- A live count region with
role="status"reading"{count} items"(e.g."0 items","3 items").
The starter renders the static shell and seeds the hook stub, but none of the buttons do anything — your job is to implement the hook and the handlers so the UI is fully interactive.
Requirements
- Implement a useArray(initial) custom hook inside App.tsx that returns { items, push, removeAt, clear }.
- push(value) appends to the array immutably; removeAt(index) removes one element at that index; clear() empties the array.
- Render a text input with placeholder "New item" and an Add button that pushes the trimmed input value (ignoring empty/whitespace) and clears the input.
- Render each item in a list with a per-row Remove button that removes that specific item.
- Render a Clear button that empties the list.
- Show the current count in an element with role="status" formatted as "{count} items".
Hints (3)
- Keep the array in useState inside the hook and wrap push/removeAt/clear in useCallback so their identities stay stable. Use functional updates (prev => ...) so you don't depend on the latest items in the closure.
- removeAt should filter by index: prev.filter((_, i) => i !== index). Pass the row's index into each Remove button's onClick.
- Track the input value in its own useState in App. On Add, trim it, bail if empty, push it, then reset the input to "". The count comes straight from items.length.
Topics
- React
- React Hooks
Asked at
BrowserStack · Myntra · Zomato · Postman · Nykaa · Razorpay
