React State, Events, Lists and Conditional Rendering: Follow One Click
Follow one click through a React counter, render by render: what useState hands back, why a plain variable never updates the page, ternaries and &&, map with keys, and the index-as-key bug that moves a typed note to the wrong task.
What you will learn
- Explain what useState returns and where the value really lives
- Follow a click from the event handler to a new render and a small page update
- Show or hide parts of the page with a ternary and &&
- Render lists with map and stable keys, and update a list in state without mutating it
Before you start
- React props and composition
- JavaScript arrays: map, filter and the spread operator
A React component is a function, and you never call it yourself. React calls it, takes what it returns, and draws the page. So when a user clicks a button and the score should go from 0 to 1, where is that number kept? Not in the function. React keeps it for you between calls, and that remembered value is state.
This article follows one click from the button back to the screen, counting every render, then moves on to showing and hiding things and to lists. All outputs come from the lecture's demo scripts.
What useState gives back
import { useState } from 'react'
export default function Counter() {
// state: a value React keeps for us between renders
const [count, setCount] = useState(0)
console.log('Counter renders, count =', count)
function addPoint() {
setCount(count + 1) // store 1 and render again
}
return (
<div className="card">
<h3>Score: {count}</h3>
<button onClick={addPoint}>+1 point</button>
</div>
)
}
Take line 5 apart. On the first render, React makes a slot for this component in its memory and puts the 0 in it. That 0 is used only once. useState then returns an array of two things: the current value and a setter function. The square brackets destructure them into count and setCount.
The real value lives in React, not in your function. count is only a copy of it for this one render.
On line 15, onClick={addPoint} has no round brackets. You hand React the function itself, and React calls it later, on a click.
Follow one click
The counter demo prints each step:
Counter renders, count = 0
page: Score: 0
click: +1 point
Counter renders, count = 1
page: Score: 1
When the click runs line 9, count is 0, so this is setCount(1). Is count 1 now? No. In this render it is still 0. The setter stores 1 in React and asks for a new render. React calls Counter again, line 5 runs again, and this time React already has a value in the slot, so it hands back 1 and ignores the 0. Then React compares the two renders and changes only the text that differs.
The round-bracket mistake
Write onClick={addPoint()} and the function runs while rendering. It calls the setter, the setter asks for a render, that render calls addPoint again, and React stops:
function BrokenCounter() {
const [count, setCount] = useState(0)
function addPoint() {
setCount(count + 1)
}
return <button onClick={addPoint()}>+1 point</button>
}
Too many re-renders.
Why a plain variable does not work
export default function PlainCounter() {
// plain variable: made again, as 0, every render
let count = 0
function addPoint() {
count = count + 1 // changes the variable only
console.log('clicked, count =', count)
}
return (
<div className="card">
<h3>Score: {count}</h3>
<button onClick={addPoint}>+1 point</button>
</div>
)
}
Click three times:
page: Score: 0
clicked, count = 1
clicked, count = 2
clicked, count = 3
page: Score: 0
The variable really changes, but the page still says 0, for two reasons. Nobody called a setter, so React doesn't know anything happened. And even if React rendered again, line 3 would run again and reset count to 0. A plain variable is forgotten and never asks for a render. State does both jobs.
Conditional rendering: ? and &&
import { useState } from 'react'
export default function Toggle() {
const [open, setOpen] = useState(false)
return (
<div className="card">
<button onClick={() => setOpen(!open)}>
{open ? 'Hide details' : 'Show details'}
</button>
{/* drawn only while open is true */}
{open && <p>Due Friday. Owner: Emma.</p>}
</div>
)
}
Line 9 is a ternary: condition ? a : b picks one of two, and it is asked again on every render. Line 12 uses &&: while open is false, the expression is false and React draws nothing. After the click it gives back the paragraph.
button: Show details p: none
click: Show details
button: Hide details p: Due Friday. Owner: Emma.
n && ... with n = 0 draws: "0"
The last line is the trap. With a number n, n && <p>...</p> gives back the 0 itself when n is 0, and React draws numbers, so a "0" appears on the page. Write n > 0 && ... so the left side is a real true or false.
Lists: map, keys and a new array
export type Task = { id: number; title: string; done: boolean }
export const start: Task[] = [
{ id: 1, title: 'Write report', done: true },
{ id: 2, title: 'Email Jack', done: false },
{ id: 3, title: 'Book flights', done: false },
]
import { useState } from 'react'
import { start } from './tasks'
export default function TaskList() {
const [tasks, setTasks] = useState(start)
const [onlyOpen, setOnlyOpen] = useState(false)
// worked out on every render, never stored
const open = tasks.filter((t) => !t.done)
const shown = onlyOpen ? open : tasks
function flip(id: number) {
// a NEW array, a NEW object for that task
setTasks(tasks.map((t) =>
t.id === id ? { ...t, done: !t.done } : t))
}
return (
<div className="card">
<button onClick={() => setOnlyOpen(!onlyOpen)}>
{onlyOpen ? 'Show all' : 'Show open only'}
</button>
<ul>
{shown.map((t) => (
<li key={t.id} onClick={() => flip(t.id)}>
{t.done ? '✔' : '○'} {t.title}
</li>
))}
</ul>
</div>
)
}
Line 23 maps each task to an li, so three tasks give three rows. Line 24 gives each row a key, the task's id. Think of the key as a name tag for the row. Lines 8 and 9 work out the open tasks and the shown list on every render; they are never stored.
rows: ✔ Write report | ○ Email Jack | ○ Book flights
click: Show open only
rows: â—‹ Email Jack | â—‹ Book flights
click: Email Jack
rows: â—‹ Book flights
Clicking Show open only sets onlyOpen to true. The new render has two rows with keys 2 and 3. React matches old and new rows by key: keys 2 and 3 exist in both renders, so those rows are kept, and key 1 is gone, so that one row is removed.
Clicking Email Jack calls flip(2). Lines 13 and 14 build a brand new array with map. Tasks 1 and 3 are the same objects, but task 2 becomes a new object made with the spread, with done flipped. Because the setter gets a new array, React sees the change. If you changed done inside the old array, React would get the same array back and might skip the render.
The index as the key
The classic list bug. This demo gives every row a text box, types "budget" into the first row, then deletes the first task. It runs once with key={index} and once with key={t.id}:
function Notes({ byIndex }: { byIndex: boolean }) {
const [tasks, setTasks] = useState(start)
const removeFirst = () => setTasks(tasks.slice(1))
return (
<ul>
{tasks.map((t, index) => (
<li key={byIndex ? index : t.id}>
{t.title}<input />
<button onClick={removeFirst}>x</button>
</li>
))}
</ul>
)
}
key={index} before: Write report [budget] | Email Jack [] | Book flights []
key={index} after: Email Jack [budget] | Book flights []
key={t.id} before: Write report [budget] | Email Jack [] | Book flights []
key={t.id} after: Email Jack [] | Book flights []
With index keys, key 0 still exists after the delete, so React keeps row 0 with its text box and note and just changes the text to Email Jack. Now Email Jack says "budget". With id keys, key 1 is gone, so React removes that row together with its note. Use a stable id from the data as the key, never the position.
Each component keeps its own state
App renders Counter, Toggle and TaskList side by side. Each keeps its own state (count, open, tasks), and a change re-renders only the component whose state changed. The project's npm run build passes the type check and the build with no errors.
Recap
| Idea | What to remember |
|---|---|
useState(0) | Returns the current value and a setter; the value lives in React |
| Setter | Stores the new value and asks for a new render; the variable in this render stays the same |
| Plain variable | Starts over on every render and never triggers one |
onClick={fn} | Pass the function, don't call it |
? : and && | Pick one of two, or draw something or nothing; keep the left side boolean |
| Lists | map to elements, stable id as key, build a new array with map and spread |
Try it yourself: add a Reset button to Counter that sets the count back to 0, then switch TaskList to key={index} and check that the note really jumps rows. Next up: effects, and when you don't need one.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
Watch useEffect on a timeline with real render counts: the dependency array deciding re-runs, a timer cleanup that keeps one timer alive, the leak StrictMode exposes, and two effects you should delete (a copied total and a click flag).
Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
A task board where the filter is stuck in one component, fixed by lifting it to App. Then useRef as a box React does not watch (three clicks, zero renders), a ref that refocuses an input, and the tree React DevTools shows.
Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
Four versions of an add-task form, traced with real logs: a controlled input, a classic onSubmit, a form action that gets FormData and resets itself, and useActionState with a pending button from useFormStatus, plus the draft trick that keeps typed text after an error.
React Context and Custom Hooks: Share One Value, Reuse the Logic
Replace three hops of prop drilling with a context, see the nearest Provider win, count which components re-render on a theme toggle, then pull localStorage logic into a useLocalStorage hook and break the rules of hooks on purpose.
