State with useState
Overview
Components often need to remember things: the current image in a gallery, whether a menu is open, what’s in a shopping cart. This component-specific memory is called state, and you add it with the useState hook.
Why a regular variable doesn’t work
function Counter() {
let count = 0;
function handleClick() {
count = count + 1;
console.log(count); // 1, 2, 3… in the console
}
return <button onClick={handleClick}>Clicked {count} times</button>; // always 0
}The console shows the variable increasing, but the screen never changes. Two problems:
- Changing a local variable doesn’t trigger a render. React has no idea anything changed.
- Local variables don’t survive renders. Even if the component did re-render,
let count = 0would run again and reset it.
useState solves both: it keeps a value between renders, and its setter triggers a new render.
Using useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}useState(0) returns an array of two things, which you destructure:
count— the current state value (0on the first render),setCount— a function that updates it.
Name them [something, setSomething] by convention.
Here’s what happens when you click:
- React renders
Counter.useState(0)returns[0, setCount]. - You click. The handler calls
setCount(0 + 1). - React stores
1and schedules a re-render. - React calls
Counteragain. This timeuseState(0)returns[1, setCount]— the initial value is ignored after the first render. - React updates the DOM to “Clicked 1 times”.
Any kind of value
State can hold strings, numbers, booleans, arrays, objects — anything:
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const [tags, setTags] = useState(['react', 'hooks']);
const [form, setForm] = useState({ name: '', email: '' });A component can have as many state variables as it needs. Prefer several simple variables over one big object when the values change independently.
Toggling a boolean
function FaqItem({ question, answer }) {
const [isOpen, setIsOpen] = useState(false);
return (
<div>
<button aria-expanded={isOpen} onClick={() => setIsOpen(!isOpen)}>
{question}
</button>
{isOpen && <p>{answer}</p>}
</div>
);
}State is private to each instance
Render the same component twice and each copy gets its own state:
<FaqItem question="Is there a certificate?" answer="Yes." />
<FaqItem question="Can I get a refund?" answer="Within 30 days." />Opening one doesn’t open the other. State is tied to the component’s position in the tree, not to the function — React keeps a separate box of state for each place a component is rendered. (If two components need to share state, you’ll lift it up to a common parent — see Lifting state up.)
Lazy initial state
If the initial value is expensive to compute, pass a function — React calls it only on the first render:
// ✗ Reads localStorage on every render (the result is ignored after the first)
const [draft, setDraft] = useState(localStorage.getItem('draft') ?? '');
// ✓ Only reads it once
const [draft, setDraft] = useState(() => localStorage.getItem('draft') ?? '');The Rules of Hooks
Functions starting with use — useState, useEffect, useContext and your own custom hooks — are hooks. React relies on hooks being called in the same order on every render, so there are two rules:
- Only call hooks at the top level of a component or custom hook — not inside
ifstatements, loops, nested functions or after an earlyreturn. - Only call hooks from React functions — components and custom hooks, not regular JavaScript functions or classes.
function Profile({ user }) {
if (!user) return null; // early return…
const [tab, setTab] = useState('courses'); // ✗ …then a hook: the order changes between renders
}
function Profile({ user }) {
const [tab, setTab] = useState('courses'); // ✓ hooks first
if (!user) return null;
// …
}The rules-of-hooks lint rule catches these mistakes as you type. It’s switched on in the Vite template’s Oxlint config, and it’s in eslint-plugin-react-hooks if your project uses ESLint.
One exception: the
useAPI (for reading promises and context, covered in Suspense and use) can be called inside conditions. It’s the only one.
Seeing state in DevTools
Open React DevTools → Components, select a component, and you’ll see its hooks with their current values. You can even edit state there to test how the UI reacts.
Rule of thumb: if a value changes over time because of user interaction and the screen should reflect it, it’s state. If it never changes, it’s a constant. If you can calculate it from other values, it’s neither — compute it during render.
A like button and an image gallery
Write LikeButton that shows “♡ 12” and toggles between liked (“♥ 13”) and not liked (“♡ 12”) on each click, using one boolean state. Then write Gallery({ images }) that shows one image at a time with “Previous” and “Next” buttons, “Image N of M”, and disables Previous on the first image and Next on the last.
import { useState } from 'react';
export function LikeButton() {
// your code here
}
export function Gallery({ images }) {
// your code here
}import { useState } from 'react';
export function LikeButton() {
const [liked, setLiked] = useState(false);
const count = liked ? 13 : 12;
return (
<button aria-pressed={liked} onClick={() => setLiked(!liked)}>
{liked ? '♥' : '♡'} {count}
</button>
);
}
export function Gallery({ images }) {
const [index, setIndex] = useState(0);
const image = images[index];
return (
<figure>
<img src={image.src} alt={image.alt} />
<figcaption>
Image {index + 1} of {images.length}
</figcaption>
<button disabled={index === 0} onClick={() => setIndex(index - 1)}>
Previous
</button>
<button disabled={index === images.length - 1} onClick={() => setIndex(index + 1)}>
Next
</button>
</figure>
);
}Summary
- Regular variables reset on every render and changing them doesn’t re-render — that’s why you need state.
const [value, setValue] = useState(initial)gives you the current value and a setter.- Calling the setter stores the new value and asks React to re-render the component.
- Each component instance has its own, private state.
- Hooks must be called at the top level of a component or custom hook — never in conditions, loops or nested functions.