← Machine Coding

useArray

mediumreacthooksarrays
Asked at
Airbnb
Meta
Microsoft
Razorpay
Uber
Airbnb, Meta, Microsoft, Razorpay, Uber

Problem statement

Implement a useArray hook that manages an array of items with additional utility methods.

Using useArray is more convenient than plain useState when the component performs common array operations such as append, update, remove, filter, clear, and reset.

The hook should work generically with arrays of any type.

API

const {
  array,
  set,
  push,
  update,
  remove,
  filter,
  clear,
  reset,
} = useArray(initialArray);

Requirements

  • array: the current array state.
  • set(nextArray): replace the entire array.
  • push(item): append an item.
  • update(index, item): replace the item at index.
  • remove(index): remove the item at index.
  • filter(callback): keep items where callback(item, index) returns true.
  • clear(): set the array to an empty array.
  • reset(): restore the original initial array.
  • Every operation should create a new array instead of mutating the current one.

Requirements & constraints

  • →Use React hooks.
  • →Do not mutate the current array state.
  • →The hook should work with arrays of any item type.
  • →The returned methods should be safe to use across renders.

Examples

  • Example 1

    Input: const todos = useArray(['read']); todos.push('ship');

    Output: array becomes ['read', 'ship']

  • Example 2

    Input: const nums = useArray([1, 2, 3]); nums.remove(1);

    Output: array becomes [1, 3]

How to approach useArray

The strategy an interviewer expects you to reach for.

Approach useArray is a small abstraction over useState. The important rule is that no method mutates the existing array. Each method calls setArray with a new array reference.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Live React sandbox pre-wired for this component
  • Time-boxed checkpoints that mirror a real 45-minute round
  • Interviewer scoring criteria and a full reference implementation
Unlock the full solution →

Already a member? Log in to open the workspace.

More Machine Coding questions

View all Machine Coding →
Machine CodingMedium

React Tic-Tac-Toe Engine

Machine CodingMedium

Performant Image Slider

Machine CodingMedium

API Search and Render Image

Machine CodingEasy

Accessible React Tabs

Machine CodingMedium

Recursive File Explorer

Machine CodingEasy

Stopwatch

Explore related prep hubs

  • All machine coding
  • Frontend machine coding guide
  • React machine coding questions
  • UI coding interview questions
  • React UI interview questions
  • Airbnb interview
  • Meta interview
  • Microsoft interview
  • Razorpay interview
  • Uber interview