2dbi

React Increment/Decrement Counter Component

viaLeetCode

Problem Build a React counter component: display a value with buttons to increment and decrement. Provide production-quality implementations both as a class component and as a functional component with hooks.

Input / Output

  • Props: optional initialValue, step, min/max bounds, onChange callback.
  • Renders the current count and +/− buttons; clicking updates the value.

Constraints

  • Production-ready expectations: no state mutation, functional setState updates, accessible buttons (aria-labels), disabled state at bounds.

Example

  • <Counter initialValue={0} step={1} min={0} /> → clicking + three times shows 3; − at 0 stays 0 (button disabled).

Expected approach

  • Functional: const [count, setCount] = useState(initialValue); handlers use setCount(c => c + step) (updater form avoids stale-closure bugs — be ready to explain why setCount(count + 1) twice in one tick increments once). Class: this.state + this.setState((s) => …), handlers bound or arrow fields. Discussion: controlled vs uncontrolled (value from props vs internal state), useCallback for handler identity, and where lifting state up would apply.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account