Skip to main content

counter

Here's a simple React TypeScript functional component that implements a counter with increment, decrement, and reset functionality:

import React, { useState } from 'react';

const CounterApp: React.FC = () => {
const [count, setCount] = useState<number>(0);

const increment = () => setCount(prevCount => prevCount + 1);
const decrement = () => setCount(prevCount => prevCount - 1);
const reset = () => setCount(0);

return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement} disabled={count === 0}>Decrement</button>
<button onClick={reset} disabled={count === 0}>Reset</button>
</div>
);
};

export default CounterApp;

In this code:

  • We use the useState hook to create a count state variable initialized to 0.
  • Three functions increment, decrement, and reset are defined to change the state accordingly.
  • The increment function increases the count by 1.
  • The decrement function decreases the count by 1, but only if count is greater than 0.
  • The reset function sets the count back to 0.
  • We render the count and three buttons that call the respective functions when clicked.
  • The decrement and reset buttons are disabled when the count is 0 to prevent negative numbers or unnecessary resets.