← Machine Coding

useCounter II

easyreacthooksstate
Asked at
Airbnb
Atlassian
Meta
Microsoft
Swiggy
Airbnb, Atlassian, Meta, Microsoft, Swiggy

Problem statement

Implement an optimized version of the useCounter hook. The returned methods should be memoized so the same function instance is returned across re-renders.

Usage

export default function Component() {
  const { count, increment, decrement, reset, setCount } = useCounter();

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

Arguments

  • initialValue: initial counter value. Defaults to 0.

Return Value

  • count: current counter value.
  • increment(): increment by one.
  • decrement(): decrement by one.
  • reset(): reset to the initial value.
  • setCount(value): set the counter value directly.

increment, decrement, reset, and setCount must be stable function instances across re-renders.

Requirements & constraints

  • →Use React hooks.
  • →Returned method identities should remain stable across re-renders.
  • →Default initial value is 0.

How to approach useCounter II

The strategy an interviewer expects you to reach for.

Approach The state itself lives in useState. The returned methods are wrapped in useCallback with empty dependency arrays so their identity stays stable across re-renders.

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
  • Atlassian interview
  • Meta interview
  • Microsoft interview
  • Swiggy interview