Sequence NODE_181
EasyBuild a Counter Component
React
JavaScript
Technical Specification
Create a counter with + and - buttons and show the current value.
Input/Output Samples
Input:Click + three times
Output:Counter shows 3
Optimal Logic Path
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => Math.max(0, c - 1))}>-</button>
<button onClick={() => setCount((c) => c + 1)}>+</button>
</div>
);
}Architectural Deep-Dive
We initialize count with 0 and use setCount to increment or decrement. Math.max ensures it never goes below 0.