React - Counter component with useState

0 votes
55 views
added Jan 9 in React by lcjr First Warrant Officer (11,850 points)
import React, { useState } from 'react';

const CounterComponent = () => {
  // Declare a state variable named 'count' with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default CounterComponent;

 

In this example, the component maintains a state variable called count, initialized to 0. The component renders a paragraph element displaying the current count and two buttons.

Each button has an onClick event handler that calls the setCount function to update the count state based on the current value.

Clicking the "Increment" button increases the count, while clicking the "Decrement" button decreases it. The component re-renders each time the state is updated, reflecting the changes in the UI.

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...