Skip to content

Volume ITechnology

6.4.2 — State and Events: Making the Page Respond ​

A shop has an "Add to cart" button and a badge in the header that says how many items are in the cart. The customer clicks the button. The badge must change from 0 to 1.

On the last page, every component showed whatever it was handed and never changed. This page gives components memory and teaches them to react to the user. Those two ideas are called state and events, and together they are the engine of every React app.

1. Why an ordinary variable does not work ​

Here is the obvious first try. Make a counter variable, and add one when the button is clicked.

tsx
function AddToCart() {
  let count = 0

  function handleClick() {
    count = count + 1
    console.log(count)
  }

  return <button onClick={handleClick}>In cart: {count}</button>
}

Run this and click the button three times. The console prints 1, 2, 3. The number on the button stays at 0. Two separate things are wrong, and you need to understand both.

Problem one: React does not know anything changed. React draws the screen by running your component function. It runs it again only when it is told to. Changing a normal variable tells it nothing. The variable changed, but nobody asked React to look.

Problem two: even if React did run the function again, the number would reset. Each time a function runs, its local variables are created from scratch. let count = 0 would run again and put 0 back. A normal local variable cannot remember anything between runs.

So a component needs two things that an ordinary variable cannot give: a place to keep a value that survives re-runs, and a way to tell React "this value changed, draw the screen again". React gives you both in one tool.

2. useState: memory that triggers a redraw ​

tsx
import { useState } from 'react'

function AddToCart() {
  const [count, setCount] = useState(0)

  return <button onClick={() => setCount(count + 1)}>In cart: {count}</button>
}

Now the button works. Here is every piece.

useState is a hook: a special function that gives a component an ability. (Hooks always start with use. Chapter 6.4.5 explains how they work inside.) You call it with the starting value, 0.

It returns a pair (an array with two items): the current value, and a setter function that changes it. The line const [count, setCount] = ... is array destructuring from Chapter 3.6. You choose the names. By strong convention they are thing and setThing.

When the button is clicked, setCount(count + 1) does two things: it stores the new value for this component, and it tells React to run the component again. On that second run, useState(0) does not return 0. It returns the stored value, 1. The component returns In cart: 1, and React updates the screen.

The 0 passed to useState is used only the first time. After that, React ignores it and gives back what it has stored.

Here is the loop that now runs behind every click.

①Component runscount is 0, so itreturns "In cart: 0"②Screen shows itthe user seesIn cart: 0③User clicksonClick runs thehandler④Handler sets statesetCount(count + 1)asks for a new value⑤React re-runscalls the componentagain, with count = 1back to ①, now with the new value: "In cart: 1"
The loop that drives every React page. The component runs, the screen shows the result, the user does something, a handler calls the setter, and React runs the component again with the new value. You write the handler and the component. React runs the loop.

Walk around the figure once. The component runs and returns what the screen should show (①). The user sees it (②). The user clicks (③). The handler calls the setter (④). React runs the component again with the new value (⑤), which brings you back to ① with an updated screen. You write the component and the handler. React runs the loop.

The word "render" ​

When React runs your component function to find out what the screen should look like, that is called rendering. It does not mean "draw pixels". It only means "call the function and get the JSX". After a render, React compares the result with what is already on the page and changes only the parts that differ.

So "this component re-renders when its state changes" means "React calls the function again with the new state". Remember it, because it explains almost every React question.

Each copy has its own state ​

tsx
function Shop() {
  return (
    <>
      <AddToCart />
      <AddToCart />
    </>
  )
}
<AddToCart /> (first copy)count = 3<AddToCart /> (second copy)count = 0In cart: 3In cart: 0Same code, separate memory. This is why state is private to a component.
State belongs to one copy of a component, not to the component's code. Two buttons made from the same function each remember their own number. Clicking the left one leaves the right one alone.

Click the first button three times and it says In cart: 3. The second still says In cart: 0. State belongs to one copy of the component on the screen, not to the code. Two buttons made from the same function each have their own memory.

You can see why this is useful: a list of forty product cards can each remember their own "expanded" or "liked" state without any extra effort.

3. Events: how the user talks to your component ​

A user does things: clicks, types, submits a form, presses a key. In React you listen for those by giving an element a prop that starts with on, and passing a function.

tsx
<button onClick={handleClick}>Add</button>
<input onChange={handleChange} />
<form onSubmit={handleSubmit}>…</form>
<input onKeyDown={handleKey} />
<div onMouseEnter={showHint} onMouseLeave={hideHint}>…</div>

The most common ones are onClick, onChange (the user changed a field), onSubmit (a form was submitted), onKeyDown, onFocus and onBlur.

Pass the function. Do not call it. ​

This is the single most common beginner mistake, so look at it closely.

tsx
<button onClick={handleClick}>Add</button>        // correct: passes the function itself
<button onClick={handleClick()}>Add</button>      // wrong: calls it right now

With the brackets, handleClick() runs while the page is being drawn, and what it returns is given to the button. The handler runs once, at the wrong moment, before anyone clicked. If the handler returns something that is not a function, React complains: "Expected onClick listener to be a function, instead got a value of number type."

Without the brackets, you hand React the function and React calls it when the click happens.

What if you need to give the handler an argument, such as which product to add? Wrap the call in a small arrow function:

tsx
<button onClick={() => addItem(product.id)}>Add</button>

Read it as: "when clicked, run this little function, which calls addItem(product.id)." The arrow function is what you pass. It has not run yet.

The event object ​

React gives every handler one argument: an event object that describes what happened. For an input it carries the text the user typed.

tsx
import { useState } from 'react'
import type { ChangeEvent } from 'react'

function SearchBox() {
  const [query, setQuery] = useState('')

  function handleChange(event: ChangeEvent<HTMLInputElement>) {   // (1)
    setQuery(event.target.value)                                  // (2)
  }

  return (
    <input
      value={query}                                               // (3)
      onChange={handleChange}
      placeholder="Search products"
    />
  )
}
  1. The event object's type is ChangeEvent<HTMLInputElement>. The part in angle brackets says which element it came from, so TypeScript knows event.target is an input and has a value. Other common types are MouseEvent<HTMLButtonElement> for clicks and FormEvent<HTMLFormElement> for form submits.
  2. event.target.value is the text now in the box. We store it in state.
  3. value={query} makes the input show whatever is in state. This pairing is called a controlled input: React state is the single source of truth, and the input is just a display of it. Type a letter, the handler stores it, React re-renders, and the input shows the new text. It happens so fast it feels instant.

Why not let the input keep its own text, as plain HTML does? Because once the text is in state, the rest of your code can use it. You can filter a list as the user types, show "3 results", or disable a button while the box is empty. The next page builds a filter exactly this way.

Two details on forms:

tsx
function handleSubmit(event: FormEvent<HTMLFormElement>) {
  event.preventDefault()        // stop the browser from reloading the page
  // …send the data
}

A browser form submits by loading a new page by default. In a React app you take control, so you stop that with event.preventDefault() and do the work in JavaScript.

4. State is a snapshot, not a live variable ​

There is one surprise that catches nearly everyone, so meet it early. Look at this handler:

tsx
function handleClick() {
  setCount(count + 1)
  setCount(count + 1)
  setCount(count + 1)
}

You might expect the count to go up by 3. It goes up by 1.

The reason: during one render, count has one fixed value, like a photograph of the state taken when that render started. If count is 0, then all three lines mean setCount(0 + 1). The last one wins. The new value only appears on the next render, when React runs the component again.

When the next value depends on the previous one, give the setter a function instead of a value. React calls it with the latest value:

tsx
function handleClick() {
  setCount((c) => c + 1)    // +1, based on the latest value
  setCount((c) => c + 1)    // +1 again
  setCount((c) => c + 1)    // and again: the total is +3
}

Rule of thumb: if the new state is computed from the old state, use the function form. Chapter 6.4.5 shows the mechanism that makes it work.

5. State with objects and arrays: never change, always replace ​

Numbers and text are easy. A cart is a list, so let us see how state works with one. First, the type:

tsx
type CartItem = { productId: string; quantity: number }

And the state:

tsx
const [items, setItems] = useState<CartItem[]>([])

useState<CartItem[]>([]) starts with an empty list and tells TypeScript what the list will hold. Without the <CartItem[]>, TypeScript would guess the type of an empty array as never[], and you could not add anything.

Now the important rule. Never change state in place. Always give React a new value. Look at the wrong way:

tsx
function addWrong(item: CartItem) {
  items.push(item)          // changes the existing array
  setItems(items)           // gives React the SAME array
}

This does nothing visible. React decides whether to re-render by asking "is this value the same object as before?". It is the same array, just with something inside it. So React concludes that nothing changed and skips the render. (This is easy to check: we ran it. The screen stayed at 0 items.)

The right way builds a new array that contains what you want:

tsx
function addItem(productId: string) {
  setItems((prev) => {
    const existing = prev.find((i) => i.productId === productId)
    if (existing) {
      // already in the cart: make a copy of the list where this one has quantity + 1
      return prev.map((i) =>
        i.productId === productId ? { ...i, quantity: i.quantity + 1 } : i,
      )
    }
    // not in the cart yet: a new list with the old items followed by one new item
    return [...prev, { productId, quantity: 1 }]
  })
}

Read it slowly. We use the function form of setItems, because the new list depends on the old one (prev). Inside, there are two cases. If the product is already there, prev.map(...) goes through the list and returns a new list. For the matching item it returns a new object { ...i, quantity: i.quantity + 1 }. The ...i copies all the old fields, then quantity overwrites one of them. Every other item is returned as it was. If the product is not there, [...prev, newItem] makes a new list with all the old items, then the new one.

The ... (the spread operator) is the tool you will use constantly. It means "copy everything from this array or object into the new one".

Here are the four moves you will need for lists, each producing a new array:

You want toWriteNot this (it changes in place)
Add an item[...items, newItem]items.push(newItem)
Remove an itemitems.filter(i => i.productId !== id)items.splice(index, 1)
Change one itemitems.map(i => i.productId === id ? { ...i, quantity: 5 } : i)item.quantity = 5
Sort[...items].sort(compare) or items.toSorted(compare)items.sort(compare)

And for an object with objects inside, copy each level you change:

tsx
setUser({ ...user, address: { ...user.address, city: 'Lisbon' } })

This might feel like extra work. There is a good reason for it. React can only compare "same object or not" quickly. If you always create a new object when something changes, that quick test is reliable. It also means old versions are never damaged, which makes bugs far easier to find. (Later, Redux Toolkit uses a library called Immer so you can write code that looks like it changes things but still produces new objects: Chapter 6.4.7.)

6. What belongs in state, and what does not ​

State is memory that causes a redraw. Beginners tend to put too much in it. Before you add a state variable, ask three questions:

  1. Can it be worked out from other state or from props? Then do not store it. Calculate it.
  2. Is it a copy of a prop? Then do not store it. Use the prop.
  3. Does the screen change when it changes? If not, it is not state. (A timer id, for example. Chapter 6.4.5 covers useRef for that.)

The first rule matters most. Say you need the cart total.

tsx
// Wrong: a second piece of state that must be kept in step with the first.
const [items, setItems] = useState<CartItem[]>([])
const [total, setTotal] = useState(0)

Every place that changes items must also remember to update total. Forget one, and the page shows a total that does not match the cart. This is exactly the "update everything yourself" bug from the start of Chapter 6.4.1.

tsx
// Right: store the minimum, and calculate the rest during render.
const [items, setItems] = useState<CartItem[]>([])
const itemCount = items.reduce((sum, i) => sum + i.quantity, 0)

itemCount is a plain variable, recalculated every render from items. It can never be out of date, because it has no memory of its own. Store the smallest amount of data that describes the situation, and compute everything else. You will hear this called "derived state".

7. Lifting state up ​

The header badge shows the number of items. The product cards have the "Add" buttons. Both need the cart. Where should the cart state live?

If each component made its own useState for the cart, they would not agree (the badge would say 0 while a card thinks there is one item). The answer is to put the state in the closest parent that contains both, and pass it down.

Before: each keeps its own copy, so they disagree<App />no state<Header />cart = [] (its own copy)<ProductCard />cart = [mug] (its own copy)badge says 0, but the cart has 1 itemAfter: the state lives in App<App />cart = [mug] (the only copy)<Header />shows cart.length<ProductCard />calls onAdd(id)count downonAdd down (a function)
When two components need the same data, move the state to the closest parent they share. The parent passes the value down to one child and a function down to the other. Now there is only one copy, so they can never disagree.

The state lives in App. App passes the value down to the part that shows it (Header), and passes a function down to the part that changes it (ProductCard). The card calls the function, the state in App changes, App re-renders, and everything below it gets fresh props. This pattern is called lifting state up, and you will use it every day.

Here is the whole thing in one small, working app:

tsx
import { useState } from 'react'

type Product = { id: string; name: string; priceCents: number }
type CartItem = { productId: string; quantity: number }

const products: Product[] = [
  { id: 'p1', name: 'Red mug', priceCents: 1999 },
  { id: 'p2', name: 'Desk lamp', priceCents: 4500 },
]

function Header({ itemCount }: { itemCount: number }) {                    // (1)
  return <header>My Shop · Cart: {itemCount}</header>
}

function ProductCard({ product, onAdd }: { product: Product; onAdd: (id: string) => void }) {
  return (
    <article>
      <h2>{product.name}</h2>
      <p>${(product.priceCents / 100).toFixed(2)}</p>
      <button onClick={() => onAdd(product.id)}>Add to cart</button>       {/* (2) */}
    </article>
  )
}

export default function App() {
  const [items, setItems] = useState<CartItem[]>([])                       // (3)

  function addItem(productId: string) {                                    // (4)
    setItems((prev) => {
      const existing = prev.find((i) => i.productId === productId)
      return existing
        ? prev.map((i) => (i.productId === productId ? { ...i, quantity: i.quantity + 1 } : i))
        : [...prev, { productId, quantity: 1 }]
    })
  }

  const itemCount = items.reduce((sum, i) => sum + i.quantity, 0)          // (5)

  return (
    <>
      <Header itemCount={itemCount} />
      <main>
        {/* (6) */}
        {products.map((p) => (
          <ProductCard key={p.id} product={p} onAdd={addItem} />
        ))}
      </main>
    </>
  )
}
  1. Header only receives a number. It has no state and no idea where the number comes from. Easy to read, easy to reuse.
  2. The card calls onAdd with its product id. It does not know what "add" means.
  3. The one and only copy of the cart lives here, in the parent.
  4. The function that changes the cart. It uses the "replace, never mutate" rules from section 5.
  5. The count is calculated, not stored (section 6).
  6. products.map(...) makes one card per product, and key helps React keep them straight. The next page explains lists and keys properly.

Click "Add to cart" twice on the mug and the header reads Cart: 2. Follow the whole path: the click calls onAdd, which is addItem, which calls setItems, which tells React to render App again; itemCount is recalculated as 2, Header receives the new number, and the screen updates.

8. When does a component re-render? ​

Three things make a component run again:

  1. Its own state changes (a setter was called with a different value).
  2. Its parent re-renders, because the parent runs and creates it again.
  3. A context it reads changes (Chapter 6.4.6 and 6.4.8).

Point two surprises people. When App re-renders, Header and every ProductCard run again too, even if their props did not change. Usually that is perfectly fine. Running a small function is cheap, and React only touches the real page where the output differs. Do not rush to "optimise" this. Measure first. Chapters 6.4.4 and 6.4.5 explain when skipping re-renders is worth it and how.

A re-render is not a page reload and not a DOM rewrite. It only means "call the function again to get the new description."

What the interviewer will push on ​

"What is state, and how is it different from a regular variable?" State is memory that survives re-renders and that tells React to re-render when you change it. A normal local variable is recreated on each run and changing it triggers nothing. Add the one-line difference from props: props come from a parent and are read-only; state belongs to the component.

"Why do you have to use the setter instead of changing the value directly?" Two reasons: React must be told that something changed so it re-renders, and the new value must be a new object so React's "same or different" check works. A strong answer mentions both.

"Why does setCount(count + 1) three times only add one?" Because count is a snapshot for the whole render. Use the function form setCount(c => c + 1) when the next value depends on the previous one.

"Why must you not mutate state?" Because React compares by identity. Pushing into the same array and passing it back looks unchanged, so there is no re-render. Also it breaks anything that remembers old values. Replace with a new array or object using spread, map and filter.

"What is a controlled input?" One whose displayed value comes from React state (value plus onChange). React is the single source of truth, so you can validate, format or react as the user types.

"What is lifting state up?" When two components need the same data, move the state to their closest common parent and pass the value and the updater down as props.

"What causes a re-render?" A change in the component's own state, a re-render of its parent, or a change in a context it reads. Bonus: a parent re-render does re-render children even when their props are the same, and that is usually fine.

"What is derived state, and why avoid storing it?" Anything you can calculate from other state, such as a total from a list. Storing it makes two copies that can disagree. Calculate it during render.

One thing to volunteer: point out that onClick={handle()} runs at render time. It is the most common beginner bug, and naming it shows you have debugged real React.

Recall

  • A plain let variable fails for two reasons: changing it does not tell React to re-render, and it is reset on every run. useState gives memory that survives re-runs and triggers a re-render.
  • const [value, setValue] = useState(initial): the initial value is used only on the first render. Calling the setter stores the new value and asks React to run the component again. "Render" means "call the function to get the JSX", not "draw pixels".
  • Each copy of a component has its own state.
  • Events: onClick, onChange, onSubmit, and so on. Pass the function, do not call it: onClick={fn} or onClick={() => fn(id)}, never onClick={fn()}. Handlers receive an event object (type it, for example ChangeEvent<HTMLInputElement>). Use event.preventDefault() on form submit.
  • A controlled input uses value={state} and onChange that sets the state, so React is the single source of truth.
  • State is a snapshot per render: setCount(count + 1) three times adds one. Use the function form setCount(c => c + 1) when the new value depends on the old one.
  • Never mutate state; replace it. Add: [...items, x]. Remove: filter. Update one: map with { ...item, field: value }. React compares by identity, so changing the same array in place causes no re-render.
  • Store the minimum and calculate the rest (derived state). Do not copy props into state, and do not keep two copies of the same data.
  • Lift state up: put it in the closest common parent; pass the value and the setter function down as props.
  • A component re-renders when its state changes, its parent re-renders, or a context it reads changes. A parent re-render re-runs its children, which is usually fine.

Self-test: Why does a normal variable not update the screen? · What does useState(0) return, and what happens to the 0 after the first render? · Why is onClick={handleClick()} a bug? · Why does items.push(x); setItems(items) show nothing? · Where would you put the cart state if both a header and a product card need it?

Next: 6.4.3 shows how to draw lists and show or hide things, how to build forms properly, how to load data from a server the manual way, and a method for deciding how to split any screen into components and where each piece of state belongs.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet