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>
);
}
initialValue: number: Initial value of the counter state. If not provided, it should default to 0.The useCounter hook returns an object with the following properties:
count: number: The current counter valueincrement: () => void: A function to increment the counter valuedecrement: () => void: A function to decrement the counter valuereset: () => void: A function to reset the counter value to initialValue, or 0 if not providedsetCount: (value: number) => void: A function to set the counter value to value, it has the same signature as setStateThe 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,
};
}