Lesson 4 of 11 · 11 min · Building apps
State and events with useState
What you will learn
- Handle events in React and update the screen with
useState - How state behaves: snapshots, batching and updater functions
- Update objects and arrays immutably
- Decide what belongs in state, and what to derive
- Structure state to avoid duplication and impossible states
In simple words
Props come from a parent and cannot be changed. State is a component's own memory: a counter, the text in a box, whether a menu is open. When state changes, React calls the component again and shows the new result. The key habit is that you never edit state directly; you hand React the new value and it does the rest, like writing a new page number on a sticky note instead of scribbling on the old one.
Words to know
- State: data a component remembers between renders and that, when changed, triggers a re-render.
- Hook: a special function such as
useStatethat lets components use React features. - Re-render: React calling the component function again to get updated JSX.
- Immutable update: replacing a value with a new copy instead of modifying the old one.
Events
function SaveButton() {
function handleClick() {
alert("Saved");
}
return <button type="button" onClick={handleClick}>Save</button>;
}
- Attach handlers with camelCase props:
onClick,onChange,onSubmit,onKeyDown,onFocus. - Pass the function, not a call:
onClick={handleClick}(nothandleClick()); with arguments use an arrow:onClick={() => remove(id)}. - The handler receives a synthetic event:
(event: React.MouseEvent<HTMLButtonElement>) => ..., withevent.target,event.currentTarget,event.preventDefault(),event.stopPropagation(). Events bubble up as in the DOM. - Handlers are where side effects belong (save, navigate, change state), not in the render body.
- Use real
<button>and<a>elements for accessibility.
useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // initial value 0
return (
<div>
<p>You clicked {count} times</p>
<button type="button" onClick={() => setCount(count + 1)}>Click</button>
</div>
);
}
useState(initial) returns a pair: the current value and a setter. Calling the setter tells React "the state changed; render again with this value". Each Counter on the page has its own independent state. Hooks must be called at the top level of a component or another hook, never inside conditions, loops or nested functions (the "rules of hooks"; the ESLint plugin enforces them).
With TypeScript the type is inferred from the initial value; give it explicitly when it cannot be:
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "saving" | "saved">("idle");
State is a snapshot
Inside one render, count is a constant: the value at the time of that render. Calling setCount does not change the variable in the running function; it schedules a new render with the new value.
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
console.log(count); // still the OLD value
}
// after the click, count increased by 1, not 3: each call used the same snapshot value
To update based on the previous value (several updates in a row), pass an updater function:
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1); // now it adds 3: each updater receives the latest queued value
Rule: when the new state depends on the old state, use the updater form. React also batches updates in an event handler: it processes all set calls together and renders once afterwards (also inside timers and promises in React 18 and later).
Immutable updates
Never change state objects or arrays in place; React compares by reference and will not notice (or will render stale UI). Create a new object or array:
const [user, setUser] = useState({ name: "Asha", city: "Hyderabad", skills: ["sql"] });
setUser({ ...user, city: "Pune" }); // object: copy, then change
setUser((u) => ({ ...u, skills: [...u.skills, "python"] })); // nested array: copy each level
const [orders, setOrders] = useState<Order[]>([]);
setOrders((list) => [...list, newOrder]); // add
setOrders((list) => list.filter((o) => o.id !== id)); // remove
setOrders((list) => list.map((o) => (o.id === id ? { ...o, status: "paid" } : o))); // update one
Avoid push, splice, sort() (without copying), user.city = ..., delete. For deeply nested state, the Immer library lets you write mutating-looking code that produces immutable updates, or flatten your state.
What belongs in state
Ask: does this value change over time and does the screen depend on it? Then state. But keep it minimal:
| Do not put in state | Because |
|---|---|
| Values you can compute from props or other state (the filtered list, the full name, the total) | duplicated data gets out of sync; compute during render |
| Values that never change | use a constant |
| Values that change but do not affect rendering (a timer id, a previous value, a DOM node) | use useRef |
| Data copied from props | the copy goes stale; use the prop, or reset with a key |
Redundant or contradictory state (isLoading and isError and isSuccess booleans) |
use one status value |
// Bad: duplicated, can go out of sync
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [fullName, setFullName] = useState("");
// Good: derive it
const fullName = `${firstName} ${lastName}`.trim();
Store ids, not copies of objects, when something is selected: const [selectedId, setSelectedId] = useState<number | null>(null); const selected = orders.find((o) => o.id === selectedId); so that edits to the list are reflected in the selection.
Controlled inputs
Form fields are controlled by state: the state is the single source of truth, and the input shows it.
function SearchBox() {
const [query, setQuery] = useState("");
return (
<>
<label htmlFor="q">Search courses</label>
<input id="q" value={query} onChange={(e) => setQuery(e.target.value)} />
<p>You are searching for: {query}</p>
</>
);
}
value plus onChange is a controlled input; without onChange, it becomes read-only. The forms lesson covers this fully.
Lifting state up
When two components need the same state, move it to their closest common parent and pass it down with props (and callbacks up):
function Courses() {
const [query, setQuery] = useState("");
return (
<>
<SearchBox query={query} onQueryChange={setQuery} />
<CourseList query={query} />
</>
);
}
The next lesson covers context and reducers for state shared more widely.
Resetting and preserving state
State belongs to a component at a position in the tree. The same component at the same position keeps its state across renders; a different type, or a different key, resets it. Use key to reset on purpose:
<Editor key={documentId} document={doc} /> // a new document gets a fresh editor state
Structuring state well
- Group related values that change together (an object or
useReducer), and split unrelated ones. - Avoid deeply nested state; normalise lists (an object by id plus an array of ids) when many places update items.
- Avoid duplicated state; keep one source of truth.
- Model status as one value (
"idle" | "loading" | "success" | "error") instead of several booleans. - Initial value computed lazily: pass a function to avoid recomputing on every render:
useState(() => loadFromStorage()).
When a re-render happens
A component re-renders when its state changes, when its parent re-renders (by default, with the same props), or when a context it reads changes. Re-rendering is normally cheap; do not optimise early. If something is truly slow, measure with the React DevTools Profiler, then consider the React Compiler, memo, moving state down, or splitting components. Setting state to the same value (compared with Object.is) does not re-render.
Common mistakes
- Mutating state (
items.push(x); setItems(items)). - Expecting the variable to change right after
setX(snapshots). - Using the current value for sequential updates instead of the updater form.
- Storing derived data in state.
- Copying props into state.
- Several booleans for one status.
- Calling hooks conditionally or in loops.
- Calling
setStateduring render (infinite loop).
Try it yourself
- Build a counter with increment, decrement and reset; add a "+3" button using three updater calls.
- Build a to-do list: add, toggle done and delete items, with immutable updates.
- Reproduce the "count increases by 1, not 3" bug and fix it.
- Make a search box controlled by state and show a filtered list computed during render.
- Replace
isLoading,isErroranddatabooleans with a singlestatusstate.
Check yourself
Why do you use the setter from useState instead of assigning to the state variable?
React only knows state has changed when you call the setter, which schedules a re-render; assigning to the variable does nothing for the UI and breaks React's model.
Why does calling setCount(count + 1) three times add only 1?
Within a render, count is a fixed snapshot, so all three calls compute the same new value; use setCount((c) => c + 1) to chain updates.
What belongs in state and what does not?
State holds minimal data that changes and affects the screen; computed values, constants and values not used for rendering (use refs) do not belong in state.
How do you add an item to an array in state?
Create a new array: setItems((items) => [...items, newItem]), never push on the existing array.
Interview questions
What is state in React and how does it differ from props?
State is data owned by a component that changes over time and triggers re-renders; props are inputs from a parent and are read-only for the child.
What are the rules of hooks?
Call hooks only at the top level of function components or custom hooks, not in loops, conditions or nested functions, so React can match them by call order.
Why must state updates be immutable?
React detects changes by comparing references; mutating an existing object or array keeps the same reference, so React may skip rendering, and it also breaks memoisation and time-travel debugging.
Summary
- Handle events by passing functions to props such as
onClick;useStategives a value and a setter that triggers a re-render. - State is a snapshot per render; use updater functions when depending on the previous value; updates are batched.
- Update objects and arrays immutably; keep state minimal and derive the rest.
- Lift state to a common parent when components share it; use
keyto reset.
Going deeper
- React: Responding to events: handlers and propagation.
- React: State, a component's memory:
useStateexplained. - React: State as a snapshot: why updates are not immediate.
- React: Choosing the state structure: principles for good state.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.