React basics 03 · State
Events and state (useState)
What state is for, event handlers, useState line by line, controlled fields, what belongs in state and why state is a snapshot.
Loading lesson…
React basics 03 · State
What state is for, event handlers, useState line by line, controlled fields, what belongs in state and why state is a snapshot.
Loading lesson…
From lessons React basics 01 and React basics 02 you know how to show data: a component gets props and returns JSX, wraps someone else's content, shows something only sometimes and renders a list. But so far the page just stands there – it reacts to nothing. Let's take the news card from the last lesson and add a perfectly ordinary thing below its text: a "👍" button that counts how many times it was clicked.
In React you react to a click with the onClick attribute: you give it a function and React calls it every time the user clicks (in detail in section 1). We'll keep the count in a variable, as we're used to from JavaScript:
// The news card from React basics 02 – now with a button below the textfunction NewsPost() {return (<Card title="News"><p>React 19 is out!</p><LikeButton /> {/* ← the button we're about to write */}</Card>)}// A "👍" button that should count the clicksfunction LikeButton() {let likes = 0 // ❌ an ordinary variablefunction handleClick() {likes = likes + 1 // after a click, add one}// onClick={handleClick} = "after a click, call handleClick"return <button onClick={handleClick}>👍 {likes}</button>}
You click, and the button still says 0. What's going on:
LikeButton(). The variable likes is created with the value 0 and the button shows "👍 0".handleClick changes likes to 1 – in memory that really happened.NewsPost re-rendered)? The function runs from the start, including the line let likes = 0 – and the count is back at zero. An ordinary variable lives only during one call of the function.So the counter is missing two things:
State gives you both – the useState function. By the end of section 2 the counter will work.
From lesson React basics 01 you know a component is a recipe and React is the cook. Now one essential trait of that cook: they have no memory at all. After every dish they forget everything. If they kept the like count in their head (an ordinary variable), they'd start from zero on the next cooking.
That's why React keeps a notebook for them. At the start of cooking the cook reads what the notebook says ("likes: 3") and cooks accordingly. When something should change, nobody rewrites the finished dish. A new value is written into the notebook and the bell rings for the cook: "cook it again". The cook makes a new dish from the new entry.
In React you never write "change the button's text to 1". You change the data and React takes care of the screen. The cycle is always the same and the whole course revolves around it:
LikeButton reads 1 from the notebook.Then it waits for the next event and the whole round repeats.
You need state when both of these hold:
The table shows a few values from everyday apps; on the right is whether they belong in state, and if not, where they belong:
| Value | Does it change and is it visible? | In state? |
|---|---|---|
| the like count | yes – after a click | ✅ yes |
| what’s typed in a field | yes – after every letter | ✅ yes |
| whether the menu is open | yes – after clicking ☰ | ✅ yes |
| the goods in the cart | yes – after adding and removing | ✅ yes |
| the cart’s total price | it changes, but it can be calculated from the goods | ❌ no, calculate it (section 4) |
| a name the component got in props | the parent changes it, not the component | ❌ no, it’s a prop |
| a list of categories that never changes | it doesn’t change | ❌ no, an ordinary constant |
The last three rows are the most common beginner mistake: storing in state what doesn't belong there. Section 4 deals with them.
An event is something the user does on the page: clicks a button, types a letter into a field, submits a form. What for: without events a page only shows things – like a printed leaflet you can click on as much as you like and nothing happens.
How: you already know one way of writing it from the introduction – <button onClick={handleClick}>. Let's take it apart:
onClick is an attribute that says which event the button waits for: on + Click = "on a click". Every event has its own attribute and they all start with on: onClick (a click), onChange (a field changed), onSubmit (a form was submitted). There's an overview in a table a bit further down.You can write the handler as a separate function, or right on the spot:
function Greeter() {// An event handler: an ordinary function. The name handle… is a habit, not a rule.function handleClick() {alert('Hello!') // alert = a browser box with a message}return (<>{/* ① you pass the function by its name */}<button onClick={handleClick}>Say hello</button>{/* ② or you write it right there as an arrow */}<button onClick={() => alert('Bye!')}>Say goodbye</button></>)}
This is the most common mistake in all of React, so you'll see it straight away:
| ❌ Not like this | ✅ Like this |
|---|---|
onClick={handleClick()} – the parentheses call the function right during rendering. The box pops up before you click, and onClick gets only what the function returned (undefined). The click then does nothing. | onClick={handleClick} – without parentheses you pass the function itself. React keeps it and calls it only after a click. |
onClick={remove(task.id)} – the same mistake: remove is called during rendering and the task disappears by itself. | onClick={() => remove(task.id)} – when you need to pass an argument, wrap the call in an arrow. The arrow is created right away, but remove inside it runs only after a click. |
Why would a handler need an argument? Say in a task list: every row has a "Delete" button and the remove function has to know which task to delete. You tell it by passing it the task's id:
function TaskList() {const tasks = [{ id: 1, label: 'Shopping' },{ id: 2, label: 'Cleaning' },]// remove gets the id of the task to delete (the id argument)function remove(id: number) {alert('Deleting task ' + id) // really deleting from the list comes in React basics 04}return (<ul>{tasks.map((task) => (<li key={task.id}>{task.label}{/* the arrow remembers its row's task.id: "Delete" next to Cleaning calls remove(2) */}<button onClick={() => remove(task.id)}>Delete</button></li>))}</ul>)}
If it said onClick={remove(task.id)} without the arrow, both remove(1) and remove(2) would be called right during render – the pop-ups appear before you click anything.
A simple rule: an on… attribute takes a function, not its result. A function as a value is the topic of lesson JavaScript 02.
React passes the handler one argument: an object with details about what happened. It's usually called e (for event). Most often you need two things from it:
// e.target = the element the event happened on; for a field it holds what's typed<input onChange={(e) => console.log(e.target.value)} /> // prints the text after every letter// e.preventDefault() = "browser, don't do what you'd normally do" –// otherwise a form would reload the whole page after submitting<form onSubmit={(e) => { e.preventDefault(); save() }}> // save = a made-up function "save"
The events you'll meet most often. The attribute on the left, when it happens in the middle, what you typically read from the event object on the right:
| Attribute | When it happens | What you need from e |
|---|---|---|
onClick | a click on a button, a link, anything | usually nothing |
onChange | a field changes: every letter, a tick, a choice | e.target.value, for a checkbox e.target.checked |
onSubmit | a form is submitted (Enter or a button) | e.preventDefault() |
onKeyDown | a key is pressed | e.key – the key's name, say 'Enter' |
So far events can only print a message. To change something on the page after a click, they need to write into the notebook – and that's what state is for.
Every piece of state is created with the same line. You'll first see it as a template with blanks and right after that filled in – we'll fix the like counter from the introduction.
// useState is a function from React – you know import from lesson JavaScript 08import { useState } from 'react'function MyComponent() {// ─── CREATING STATE ─────────────────────────────────────// ┌ the value ┌ the function that changes it (setter) ┌ the initial valueconst [value, setValue] = useState(initialValue)// 1. WHAT DO I REMEMBER? → a name (value) and, from the initial value, its type// 2. WHAT DO I START WITH? → initialValue, used only on the first render// 3. WHEN DOES IT CHANGE? → in an event handler I call setValue(newValue)function handleSomething() {setValue(newValue) // write into the notebook and ring for the cook}// Rendering only reads: it shows what's in the notebookreturn <button onClick={handleSomething}>{value}</button>}
Three questions come with state. Ask them before you create it:
likes, text, isOpen.0, '', false, [].The answers: it remembers the like count, starts at 0, changes after a click on the button.
import { useState } from 'react'function LikeButton() {// 1. I remember likes, 2. I start at 0const [likes, setLikes] = useState(0)// 3. it changes after a click: write one more into the notebookfunction handleClick() {setLikes(likes + 1)}return <button onClick={handleClick}>👍 {likes}</button>}
Compared with the broken counter from the introduction, two things changed: useState(0) instead of let likes = 0, and setLikes(likes + 1) instead of likes = likes + 1. The table shows what each of them solved:
| Broken | Fixed | What it solved |
|---|---|---|
let likes = 0 | const [likes, setLikes] = useState(0) | the value survives the next render – React keeps it in the notebook |
likes = likes + 1 | setLikes(likes + 1) | React learns about the change and renders the component again |
LikeButton(). useState(0) looks into the notebook, finds it empty, writes the initial 0 and returns [0, setLikes]. The button shows "👍 0".handleClick. It calls setLikes(0 + 1): 1 is written into the notebook and React notes that it must render the component again.LikeButton() again. This time useState(0) finds 1 in the notebook – it ignores the initial 0 now – and returns [1, setLikes].What you see: Two counters side by side. The left one (red button) uses an ordinary variable let count = 0, the right one useState(0). Under the left one you see the variable's value in memory. The card that just rendered flashes yellow.
Try it:
The takeaway: A variable lives only during one render and changing it re-renders nothing. State survives the next render and the setter tells React to render the component again.
Loading the interactive part…
React's functions that start with use are called hooks (they "hook into" React). Two rules apply to them:
if, a loop or a nested function.Why the second one? A component can have more than one state – say a name and an age. React writes them one below the other in its notebook: line 1, line 2… But useState('Emma') doesn't tell React what the state is called. The names name and age are just your variables; React never sees them. It tells which line belongs to which useState only by the order of the calls: the first useState called gets line 1, the second line 2. See what happens when you hide one of them inside an if:
// ❌ don't – a shortened example, JSX left outfunction Profile({ isLoggedIn }) {if (isLoggedIn) {// called only when the user is logged inconst [name, setName] = useState('Emma')}const [age, setAge] = useState(30)// …}
isLoggedIn is true. Both useState calls run: the name gets line 1 ('Emma'), the age line 2 (30).isLoggedIn is false. The useState for the name is skipped. The useState for the age is now the first call, so it would get line 1 – which holds 'Emma'. The age would suddenly be the text “Emma”.React doesn't allow such a mix-up: it notices that the hooks were called differently from last time and the app crashes with an error (for example Rendered fewer hooks than expected). So always call all your hooks, at the top of the component, and put the if below them – for example into the JSX that decides what to show:
// ✅ do – both useState calls run on every render, in the same orderfunction Profile({ isLoggedIn }) {const [name, setName] = useState('Emma') // always line 1const [age, setAge] = useState(30) // always line 2if (!isLoggedIn) {return <p>Age: {age}</p> // a condition below the hooks is fine}return <p>{name}, age: {age}</p>}
What for: almost every app has fields – search, sign-in, a new task. For a component to work with the typed text (show it, check it, send it), it has to have it in state.
How: the field gets two things. value tells it what to show (the value from state), and onChange writes the new text into state after every letter. Such a field is called controlled: state controls what's in it.
function NameInput() {const [name, setName] = useState('') // 1. I remember the text, 2. I start emptyreturn (<><inputvalue={name} // the field shows what's in stateonChange={(e) => setName(e.target.value)} // 3. after every letter, write the new text/><p>Hello, {name}!</p> {/* the text can be used straight away */}</>)}
What happens when you type the letter "A":
onChange handler.e.target.value holds the text the field would have: 'A'. The handler writes it with setName('A').name is 'A', the field gets value="A" and below it is "Hello, A!".Other fields work the same way; they just differ in which attribute they carry and what's read from the event. The table shows the most common ones:
| Field | Attribute with state | What to write in onChange |
|---|---|---|
<input /> | value={text} | setText(e.target.value) |
<textarea /> | value={note} | setNote(e.target.value) |
<input type="checkbox" /> | checked={agree} | setAgree(e.target.checked) |
<select> | value={color} | setColor(e.target.value) |
What you see: A controlled name field. Below it a greeting, the character count and a Clear button. State holds only what's typed in the field – everything else is calculated from it.
Try it:
setName('') and the field empties – because it shows the state.The takeaway: The field and the text below it read from the same state, so they never contradict each other. Clearing the field means changing the state, not touching the field.
Loading the interactive part…
The greeting demo had a single piece of state – the text in the field. Neither the greeting nor the character count is in state, yet they change. They're calculated from name on every render. That's the most important rule of state: state holds only what can't be calculated from something else.
| ❌ Not like this: two pieces of state | ✅ Like this: one piece of state and a calculation |
|---|---|
|
|
On the left the same data is stored twice (the list and its length). Every function that changes the list has to remember the count too – and one day it gets forgotten. Then the page says "3 items" next to two. It's the same trap as the manual page updates from the introduction of lesson React basics 01. On the right the count is calculated from items on every render, so it can't drift apart from it. (Writing useState<Item[]>([]) tells TypeScript what the array will hold – it can't tell from an empty array. Item is a made-up item type here. [...items, item] is spread (the three dots) from JavaScript 05: a new array with the existing items and the new one at the end.)
Before you store something in state, try these questions. If the answer to any of them is "yes", it doesn't belong in state:
| Question | If yes | Example |
|---|---|---|
| Can it be calculated from other state or props? | calculate it during render | const total = items.reduce(…) |
| Does it come in props and the component doesn’t change it? | use the prop | <Greeting name={name} /> |
| Does it never change? | a constant outside the component | const CATEGORIES = ['fruit', 'vegetables'] |
This is where almost every beginner gets stuck. The setter doesn't change the variable you have in hand. It writes the new value into the notebook, and you'll see it only in the next render, in a new variable.
Think of a render as a photo. On every render the component is photographed together with all the state values. The event handlers created during it hold that photo – and a photo doesn't change afterwards. When the setter writes a new value, React takes a new photo, but a handler from the old one still sees the old value. (Lesson JavaScript 10 called this "every render is a snapshot".)
// inside a component: state at the top, the click handler below it (the button calls it through onClick)const [count, setCount] = useState(0)function addThree() {setCount(count + 1) // count is 0 in the photo → write 0 + 1 = 1setCount(count + 1) // count is still 0 → write 0 + 1 = 1setCount(count + 1) // count is still 0 → write 0 + 1 = 1console.log(count) // prints 0 – the photo didn't change}// in the component's JSX: <button onClick={addThree}>+3</button>// After the click the screen shows 1, not 3.
All three calls read count from the same photo, where it's 0. On top of that, React collects the writes from one handler and renders once, when the handler finishes (this is called batching). A one written three times is still a one.
When the new value builds on the previous one, don't pass the setter a value but a function. React gives it the freshest value from the notebook – including the one the previous call wrote there a moment ago. Such a function is called an updater:
// inside the same component – just the fixed handlerfunction addThree() {// ┌ prev = the current value in the notebook (React supplies it)setCount((prev) => prev + 1) // 0 → 1setCount((prev) => prev + 1) // 1 → 2setCount((prev) => prev + 1) // 2 → 3}// After the click the screen shows 3.
The name prev (for previous) is a habit – it can be anything, say c. The only difference is where the value comes from:
| Written as | Where it takes the value from | After three calls |
|---|---|---|
setCount(count + 1) | from the photo of the render in which the handler was created | 1 |
setCount((prev) => prev + 1) | from the notebook, at the moment the write is carried out | 3 |
What you see: Two counters. The top button calls setA(a + 1) three times, the bottom one the updater setB(prev => prev + 1) three times. Next to the bottom one is a button that adds 10 and straight away shows b in a box.
Try it:
a grows by only 1 – all three calls saw the same photo.b grows by 3 – each updater got the value after the previous one.The takeaway: The setter changes the notebook, not the variable in your hand. When you build on the previous value, use an updater.
Loading the interactive part…
The same trap waits in code that runs later – in a setTimeout timer (lesson JavaScript 07) or after a response from a server. The function in the timer takes the photo of the render in which it was created:
// inside a component with the count state – both functions are click handlersfunction addLater() {// ❌ after 2 s it writes count from the photo + 1 – clicks in the meantime are lostsetTimeout(() => setCount(count + 1), 2000)}function addLaterRight() {// ✅ the updater takes the current value only after 2 s, when it's actually carried outsetTimeout(() => setCount((prev) => prev + 1), 2000)}// in the component's JSX:// <button onClick={addLater}>+1 in 2 s</button>// <button onClick={addLaterRight}>+1 in 2 s (updater)</button>
When you click three times quickly, all three timers in the first version have a photo with count = 0 and all of them write 1. In the second version each one takes the value after the previous one and the result is 3.
What you see: Two buttons, each adds 1 only after two seconds. The top one writes the value from the photo, the bottom one uses an updater.
Try it:
The takeaway: Code that runs later holds an old photo. An updater reads the current value at the moment it's carried out.
Loading the interactive part…
This section puts the lesson together into steps to come back to when you add state to your own component. You'll find the same pattern in the Cheat sheets on the React tab.
// the file src/components/MyComponent.tsx – replace MyComponent, value, initialValue, … with your own namesimport { useState } from 'react'function MyComponent() {// 1. WHAT I REMEMBER and 2. WHAT I START WITHconst [value, setValue] = useState(initialValue)// TypeScript can't tell the type from an empty initial value → write it:// useState<string | null>(null)// Whatever can be calculated, calculate – it doesn't belong in stateconst derived = computeFrom(value) // computeFrom = a made-up function// 3. WHEN IT CHANGES: an event handler calls the setter – pick one of the two forms:function handleEvent() {// a) the new value doesn't depend on the previous one → pass the valuesetValue(newValue)// b) the new value builds on the previous one → an updater (section 5)// change = a made-up function that computes the new value from the previous one// setValue((prev) => change(prev))}return <button onClick={handleEvent}>{derived}</button> // pass the function, don't call it}// use in a parent: <MyComponent /> – every use has its own state
The most common kinds of state in one place. What you want on the left, creating the state in the middle, changing it on the right:
| I want… | State | Change |
|---|---|---|
| a counter | const [count, setCount] = useState(0) | setCount((c) => c + 1) |
| a toggle (open/closed) | const [isOpen, setIsOpen] = useState(false) | setIsOpen((o) => !o) |
| a text field | const [text, setText] = useState('') | onChange={(e) => setText(e.target.value)} |
| a checkbox | const [agree, setAgree] = useState(false) | onChange={(e) => setAgree(e.target.checked)} |
| a choice from a list | const [color, setColor] = useState('red') | onChange={(e) => setColor(e.target.value)} |
| the selected item | const [selectedId, setSelectedId] = useState<number | null>(null) | setSelectedId(item.id) |
Arrays and objects in state (a task list, a cart) have their own recipes in the next lesson, React basics 04.
count = …).on… (onClick={handle}), not its result.value and onChange.The state is ready, so are the click handlers – you just call the setter in them.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The challenge practises sections 1 to 4: controlled fields, event handlers and values that are just calculated. For every piece of state, first tell yourself: what I remember, what I start with and when it changes – and whether it can't simply be calculated. You'll find the template in sections 2 and 6.
A form with a name and a consent: fields controlled by state, the number of characters left and a button that can be pressed once everything is filled in. What exactly should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
on…, don't call it. Pass an argument with an arrow () => remove(id).value from state and an onChange that writes into state.setX((prev) => …).