Lesson 7 of 37State
useState
Give components memory with useState, and understand exactly when and why React re-renders.
Everything interactive in React (a counter, a form, an open menu, a selected tab) is state: data a component remembers that can change while the user interacts with it. You have been using useState in demos already. This lesson explains what it actually does, which is the foundation for every hook and every "why didn't my screen update?" bug you will debug.
Why a normal variable does not work
Here is a counter written with a plain let. Click the button a few times and watch the log below the preview.
The log goes 1, 2, 3, but the button stays at 0. Two separate things are wrong:
- Changing a local variable does not tell React anything. React has no idea it should re-render, so the screen never updates.
- Local variables do not survive a re-render. Even if something else caused a re-render, React would call
App()again, which runslet count = 0again from scratch.
State fixes both: it is a value React stores for you between renders, and changing it through a setter triggers a re-render.
let count = 0 outside the component (to module level) so it survives. The log works, but what is still wrong?useState: a value plus a setter
useState(0) returns an array of exactly two things, which you name with array destructuring:
count: the current value for this render. On the first render it is the initial value,0.setCount: a function that stores a new value and asks React to re-render.
The naming convention is [thing, setThing]. Functions whose names start with use are called hooks: they let a component "hook into" features React manages, like state.
Here is what happens on a click:
The handler calls setCount(count + 1), which is setCount(1). Nothing on screen has changed yet.
The initial value is only used on the first render. After that, useState returns whatever was last stored.
The rules of hooks
React does not know your state's variable names. It tracks state by the order hooks are called inside a component: first useState call, second useState call, and so on. So two rules keep that order identical on every render:
- Call hooks only at the top level of a component (or of a custom hook). Never inside
if, loops or nested functions. - Call hooks only from React function components or custom hooks, not from regular functions.
function Profile({ isAdmin }: { isAdmin: boolean }) {
// Wrong: on some renders this hook is skipped, shifting every hook after it
if (isAdmin) {
const [panelOpen, setPanelOpen] = useState(false);
}
// Right: always call it, then use the value conditionally
const [panelOpen, setPanelOpen] = useState(false);
// ...
}The ESLint plugin eslint-plugin-react-hooks (included in Vite and Next.js templates) flags these mistakes for you.
Multiple pieces of state
A component can call useState as many times as it needs. Keep separate values that change independently in separate state variables.
Do not store anything you can compute from other state or props. If you have firstName and lastName, write const fullName = firstName + " " + lastName during render. A separate fullName state would have to be kept in sync by hand, and one day it will not be.
The user clicks the button twice. What does the button say?
function Toggle() {
const [on, setOn] = useState(false);
return (
<button onClick={() => setOn(!on)}>
{on ? "ON" : "OFF"}
</button>
);
}State belongs to each instance
State is not attached to the function. It is attached to each place the component appears in the tree. Render <Counter /> twice and you get two independent counters.
Each Counter in the tree gets its own count. React keeps them in separate slots.
State is also private. The parent App cannot read either count. If the parent needs it (say, to show a total), the state has to move up into the parent, which is the lifting state up lesson.
<Counter /> in three places and click the second one 5 times. What do the three show?Initial state from a function
Sometimes computing the initial value is expensive, like reading and parsing saved data. Writing useState(loadDrafts()) calls loadDrafts() on every render, even though React only uses the result on the first one. Pass the function itself instead and React calls it once:
// Runs loadDrafts() on every render, then throws the result away
const [drafts, setDrafts] = useState(loadDrafts());
// Runs loadDrafts() only on the first render
const [drafts, setDrafts] = useState(loadDrafts);
const [prefs, setPrefs] = useState(() => JSON.parse(localStorage.getItem("prefs") ?? "{}"));This is called an initializer function (or lazy initial state). Cheap values like 0, "" or [] do not need it.
Match the code to what it does.
Counter with limits
Build a counter.
- A
<p>showingCount: 0to start. - Three buttons:
Increment(adds 1),Decrement(subtracts 1) andReset(back to 0). - The count must never go below 0: the
Decrementbutton is disabled while the count is 0.
Count: 2 [Increment] [Decrement] [Reset]Bio with a character limit
Build a bio field with a 20-character limit.
- A
<textarea aria-label="Bio">controlled by state. - Below it, a
<p>with the classcountershowinglength/20, for example5/20. - When the text is longer than 20, the counter also gets the class
over(so itsclassNameiscounter over). - A
Savebutton that is disabled when the bio is empty or over the limit.
[hello ]
5/20 [Save]- state
- Data a component remembers between renders. Changing it with the setter triggers a re-render.
- useState
- The hook that returns
[value, setValue]. The argument is the initial value, used only on the first render. - re-render
- React calling your component function again to get fresh JSX, usually because state changed.
- rules of hooks
- Call hooks only at the top level of components or custom hooks, never in conditions or loops, so their order is stable.
- initializer function
- Passing a function to
useState(fn)so an expensive initial value is computed only once.