Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Hooks

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Hooks

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

From click to new render Render 1 Score: 0 click addPoint() setCount(1) React stores 1 Render 2 Score: 1 React compares render 1 and render 2 only the score text differs page: change "0" to "1", leave the button alone
The setter does not change the variable. It stores the new value in React and asks for a new render.

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 []
Index keys versus id keys after a delete key = index key = t.id key 0: Email Jack [budget] key 1: Book flights [] the note stays with position 0 key 2: Email Jack [] key 3: Book flights [] key 1 is gone, its row and note go with it
After deleting Write report. Positions change when the list changes; ids don't.

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

IdeaWhat to remember
useState(0)Returns the current value and a setter; the value lives in React
SetterStores the new value and asks for a new render; the variable in this render stays the same
Plain variableStarts 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
Listsmap 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.

Keep going in React · 48 of 59

Previous
Copy Without the AI Tells: A Copy Pass on a Landing Page
Next post
React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • What useState gives back
  • Follow one click
  • The round-bracket mistake
  • Why a plain variable does not work
  • Conditional rendering: ? and &&
  • Lists: map, keys and a new array
  • The index as the key
  • Each component keeps its own state
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.