The useState hook introduces reactive state to functional components. When state changes, React automatically re-renders the component.
1. Counter with useState
⊞Code Example
import React, { useState } from 'react';
export default function InteractiveCounter() {
const [count, setCount] = useState(0);
return (
<div className="p-6 bg-slate-900 border border-slate-800 rounded-2xl text-center space-y-4 max-w-xs mx-auto">
<h2 className="text-xl font-bold text-white">Current Count</h2>
<p className="text-4xl font-extrabold text-emerald-400">{count}</p>
<div className="flex justify-center gap-2">
<button
onClick={() => setCount(prev => prev - 1)}
className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl font-bold"
>
- Decrement
</button>
<button
onClick={() => setCount(prev => prev + 1)}
className="px-4 py-2 bg-emerald-500 hover:bg-emerald-600 text-white rounded-xl font-bold"
>
+ Increment
</button>
</div>
</div>
);
}
