Octagram Labs
JavaScriptData StructuresReact
Sign in
← Back to problems

useCounter Logic

Hooks Logicmedium

Course · Section 10: A Closer Look at Functions · Lecture 144: Closures

Implement `useCounter(initial)` returning an object with `increment()`, `decrement()`, `reset()`, and `value()`, keeping the count private (the logic behind a useState counter hook).

Examples

Input: useCounter(0): increment, increment, decrement, value, reset, value
Output: [1, 0]
After +1 +1 -1 the value is 1; reset returns it to the initial 0.

Sample tests

Input: increment/decrement/reset
Output: [1,0]
Input: starts at initial
Output: 6

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Returning the count by value instead of through a value() accessor freezes it.

Learning resources

  • React: Reusing Logic with Custom Hooks
Approach & explanation (try first)

The closure keeps count private and the returned methods mutate it, mirroring a custom counter hook's behavior.

Loading...
⌘/Ctrl + Enter

Run your code to see results.