React · Lesson 4 of 7
State with useState
Making components interactive with the useState hook.
State is data that a component remembers between renders and that can change — a counter, the text in a search box, whether a menu is open.
const [count, setCount] = React.useState(0);
useState(initial)returns the current value and a setter function.- Calling the setter schedules a re-render with the new value.
- Never change state directly (
count = 5does nothing useful). Always call the setter. - When the new value depends on the old one, pass a function:
setCount(c => c + 1). - For arrays and objects, create a new copy:
setItems([...items, newItem]).
Hooks must be called at the top level of a component — not inside loops or if statements.
Try it yourself
Edit the code and press Run (or Ctrl/⌘ + Enter). Code runs only in your browser, in a sandbox.
Key points
- useState returns [value, setValue].
- Setting state re-renders the component.
- Copy arrays/objects instead of mutating them.
Quick check
What happens when you call a state setter?
Updating state tells React to render the component again with the new value.
Practice task
Build a counter with + and − buttons that never goes below 0.
Interview corner
Why use the functional form setCount(c => c + 1)?
Updates are batched; the function form always receives the latest value, avoiding bugs when several updates happen in one event.
What are the Rules of Hooks?
Call hooks only at the top level of components or custom hooks — never inside loops, conditions or nested functions — so React can match them between renders.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.