logo

Simple Counter

A simple counter component using React's useState hook.

8 Stars

Code

const [count, setCount] = useState(0);

const increment = () => {
  setCount(count + 1);
};

const decrement = () => {
  setCount(count - 1);
};

return (
  <div>
    <button onClick={increment}>Increment</button>
    <span>{count}</span>
    <button onClick={decrement}>Decrement</button>
  </div>
);

Explanation

This code defines a simple counter component using React's useState hook. It maintains a count state variable initialized to 0 and provides two functions, increment and decrement, to update the count state. The component renders three elements: two buttons for incrementing and decrementing the count, and a span to display the current count value.