useState — giving components memory
Components need to remember things
So far our components just display data. But real UIs change — a counter goes up, a menu opens, a form fills in. For a component to remember and update a value, React gives you state, through a tool called useState.
What is state?
State is data that belongs to a component and can change over time. When state changes, React automatically re-renders the component to show the new value. That automatic update is the magic.
Using useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
Let me break down that one important line:
const [count, setCount] = useState(0);
useState(0)→ creates a state value starting at0.count→ the current value (read it).setCount→ the only way to change it.
Why must I use setCount? Why not count = count + 1?
This is the most important rule in React. If you write count = count + 1 directly, React does not know anything changed, so the screen never updates. Calling setCount(...) does two things: it updates the value and tells React "re-draw this component".
Never change state directly — always use its setter function.
More examples
const [name, setName] = useState("");
const [isOpen, setIsOpen] = useState(false);
setIsOpen(true); // open a menu
setName("Riya"); // set a name
State = a component's changeable memory.
useStategives you a value and a setter; always use the setter so React re-renders. This is the heart of interactive React.