- Published on
useCounter Hook React

useCounter Hook React
useCounter Code and Usage
useCounter is a hook to manage a numeric counter.
import { useState } from "react";
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount((prevCount) => prevCount + 1);
};
const decrement = () => {
setCount((prevCount) => prevCount - 1);
};
return {
count,
increment,
decrement,
};
};
// Usage
const CounterExample = () => {
const { count, increment, decrement } = useCounter();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};