Building a simple counter app in React is the perfect way to master state management. Today, I built a functional Counter application that demonstrates the basics of React's useState hook.
The Concept
The application features a central display showing the current count, starting at zero. Users can interact with two primary buttons: an 'Increment' button to increase the value, and a 'Decrement' button to decrease it.
Key Logic and Constraints
The core of this project relies on the useState hook to track the count value dynamically. For the increment functionality, the handler function simply updates the state by adding one.
To ensure the application remains robust, a constraint was implemented on the decrement logic. The state is only updated if the current count is greater than zero, effectively preventing the number from dropping into negative values.
Why It Matters
This simple project reinforces the importance of conditional rendering and state boundaries. By controlling how and when user input modifies data, we ensure a smooth and logical user experience.
import { useState } from "react"; function Counter() { const [i,setCount] = useState(0) function increment() { setCount(i + 1); } function decrement() { if (i>0){ setCount(i - 1); } } return( <div> <h1> Counter : {i}</h1> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> </div> ) } export default Counter; 
