useState is a React Hook used to store and update data in a component. When the state changes, React updates the UI.
1. Basic syntax
const [value, setValue] = useState(initialValue);
value — current state value.
setValue — function to update the state.
useState(initialValue) — sets the initial value.
2. Example: Counter
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
Decrement
</button>
<button onClick={() => setCount(0)}>
Reset
</button>
</div>
);
}
How it works:
- useState(0) sets the initial count to 0.
- setCount(count + 1) increases the count.
- setCount(count - 1) decreases the count.
- setCount(0) resets it to zero.
Top comments (0)