Implement a useCounter hook that manages a counter state, with some additional convenience utility methods.

exportdefaultfunction 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

Returns

The useCounter hook returns an object with the following properties:

Editorial

Solution

The useCounter hook uses useState to manage the number state. The setter functions can be implemented in terms of setValue from the useState hook.

import { useState } from 'react';

export default function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  return {
    count,
    increment: () => setCount((x) => x + 1),
    decrement: () => setCount((x) => x - 1),
    reset: () => setCount(initialValue),
    setCount,
  };
}