State with useState
useState gives a component a piece of data that persists
across re-renders, and a function to update it.
Example: a counter, and why it actually updates on screen
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}
useState(0) returns two things: the current value
(count, starting at 0) and a function to change it
(setCount). Calling setCount(count + 1) doesn't
just change a variable quietly in the background — it tells React
"something changed, please re-run this component and update the screen
to match." That re-run-and-redraw step is the entire mechanism behind
every interactive React UI, from a simple counter to a full form.
Why you can't just reassign a normal variable instead
let count = 0;
count = count + 1; // this changes the variable, but the screen never updates
A plain variable change is invisible to React — nothing tells it to
re-run the component. useState's update function is what
actually connects a data change to a visible screen update; that
connection is the entire reason it exists instead of an ordinary
variable.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}
Renders "Count: 0" with an Add button; each click increments the displayed count by 1.