Skip to content

Volume ITechnology

6.4.3 — Lists, Conditions, Forms, Loading Data, and Thinking in React ​

A shop page has to do four jobs. It shows a list of products. It shows "Sold out" only on some of them. It lets the customer type into a form. And it loads the products from a server, which takes time and sometimes fails.

Pages 6.4.1 and 6.4.2 gave you components, props, state and events. This page uses them to do those four jobs. Then it teaches the method that professionals use to decide how to split any screen into components, and where the state goes.

1. Drawing a list ​

A cart has many items. You do not write one piece of JSX per item. You keep the items in an array, and you turn the array into JSX with .map().

tsx
type Product = { id: string; name: string; priceCents: number; inStock: boolean }

const products: Product[] = [
  { id: 'p1', name: 'Red mug', priceCents: 1999, inStock: true },
  { id: 'p2', name: 'Desk lamp', priceCents: 4500, inStock: false },
  { id: 'p3', name: 'Notebook', priceCents: 650, inStock: true },
]

function ProductList() {
  return (
    <ul>
      {products.map((p) => (                                    // (1)
        <li key={p.id}>                                         {/* (2) */}
          {p.name}: ${(p.priceCents / 100).toFixed(2)}
        </li>
      ))}
    </ul>
  )
}
  1. .map() goes through the array and returns a new array. Each item of the new array is a piece of JSX. React knows how to draw an array of JSX pieces, one after the other. So the curly braces { ... } hold an array, and React draws all of it.
  2. key={p.id} is a label that is unique for each item. More about it in a moment. Without it, React prints a warning in the console.

This draws three list items: Red mug: $19.99, Desk lamp: $45.00 and Notebook: $6.50.

Notice that you used plain JavaScript (map) and not a special template language. This is the idea from page 6.4.1 again: the UI is a value, and you build it with ordinary code. To show only the products that are in stock, filter first and map second:

tsx
{products.filter((p) => p.inStock).map((p) => (
  <li key={p.id}>{p.name}</li>
))}

What key is for ​

Imagine a customer has typed a gift note next to the first product, "Red mug". Then they delete that row. What should React do?

React has to match "the list from last render" with "the list from this render". It cannot read your mind, so it uses the key as a name tag. A row with the same key is treated as the same row, so its state and its typed text stay with it. A row whose key disappeared is removed.

If you do not give a good key, React falls back to the position in the list. And that causes a real bug. We ran this experiment, with a text box in every row. The customer types "gift wrap" into the first row, then deletes the first row:

text
key = array index (wrong):
  before delete:  Red mug=[gift wrap] | Desk lamp=[]  | Notebook=[]
  after delete:   Desk lamp=[gift wrap] | Notebook=[]

key = product id (right):
  before delete:  Red mug=[gift wrap] | Desk lamp=[]  | Notebook=[]
  after delete:   Desk lamp=[]  | Notebook=[]

With the index as key, the note "gift wrap" jumped to the Desk lamp. React saw "position 0 is still there", so it kept the text box at position 0 and only changed the name next to it. With the product id as key, React knew the Red mug row was gone and removed it together with its text box.

The rules for keys are short:

DoDo not
Use a stable id from your data (p.id)Use Math.random() (a new key on every render makes React rebuild every row)
Make it unique among siblings in that one listUse the array index when the list can be re-ordered, filtered or deleted from
Put it on the outermost element returned inside mapForget it and ignore the warning

An index is acceptable only for a list that never changes order and never has items added or removed in the middle. When in doubt, use the id.

A key is not passed to your component as a prop. If the component needs the id, pass it separately (id={p.id}). Page 6.4.4 shows exactly how React uses keys when it compares two trees.

2. Showing something only sometimes ​

The "Sold out" label must appear only when a product is not in stock. In JSX, you decide with ordinary JavaScript. There are four ways, and each fits a different situation.

Way 1: a ternary, when there are two choices ​

tsx
<p>{p.inStock ? 'Ready to ship' : 'Sold out'}</p>

Read it as: "if in stock, this text, otherwise that text". A ternary is an expression, so it can sit inside the curly braces. A plain if statement cannot, because braces in JSX hold expressions only.

Way 2: &&, when it is either something or nothing ​

tsx
{!p.inStock && <span className="badge">Sold out</span>}

a && b gives b when a is true, and gives a (which is false) when a is false. React draws nothing for false. So the badge appears only for products that are not in stock.

The trap. Be careful when the left side is a number:

tsx
{items.length && <CartSummary items={items} />}       // wrong when the cart is empty

When the cart is empty, items.length is 0. 0 && anything gives 0. And React does draw the number 0 on the page. (We checked: it prints a visible 0.) The customer sees a mysterious zero. Always make the left side a real true-or-false value:

tsx
{items.length > 0 && <CartSummary items={items} />}   // right

Way 3: return early, when a whole component has a different shape ​

tsx
function ProductCard({ product }: { product: Product }) {
  if (!product.inStock) {
    return <p>{product.name} is sold out.</p>       // the rest never runs
  }

  return (
    <article>
      <h2>{product.name}</h2>
      <button>Add to cart</button>
    </article>
  )
}

A component may use if before it returns, because that is plain JavaScript outside the JSX. A component may also return null, which means "draw nothing".

Way 4: pick one of several ​

When a thing has more than two possible situations, such as the loading states in section 4, store the situation in a variable and pick with if or an object:

tsx
function OrderBadge({ status }: { status: 'pending' | 'shipped' | 'delivered' }) {
  const label = { pending: 'Waiting', shipped: 'On the way', delivered: 'Arrived' }[status]
  return <span>{label}</span>
}

If you later add a fourth status such as 'returned' and forget to add it to that object, TypeScript refuses to compile the lookup. That is one of the reasons we use TypeScript: it finds the forgotten case before a customer does.

One last point. Not drawing something (returning null or false) is different from hiding it with CSS. A component that is not drawn is removed from the page, and its state is thrown away. A component hidden with display: none still exists and keeps its state. Pick the one you need.

3. Forms ​

A form with several fields needs a lot of state. It also has to show errors. Here is the complete method, step by step. The scenario is the checkout form of our shop.

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

type CheckoutValues = {
  name: string
  email: string
  country: string
  giftWrap: boolean
  note: string
}

const empty: CheckoutValues = { name: '', email: '', country: 'PT', giftWrap: false, note: '' }

function validate(v: CheckoutValues): Partial<Record<keyof CheckoutValues, string>> {   // (1)
  const errors: Partial<Record<keyof CheckoutValues, string>> = {}
  if (v.name.trim() === '') errors.name = 'Please enter your name.'
  if (!v.email.includes('@')) errors.email = 'That does not look like an email.'
  return errors
}

export function CheckoutForm({ onSubmit }: { onSubmit: (v: CheckoutValues) => void }) {
  const [values, setValues] = useState<CheckoutValues>(empty)                           // (2)
  const [errors, setErrors] = useState<ReturnType<typeof validate>>({})                 // (3)

  function handleChange(
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
  ) {
    const { name, type, value } = e.target                                              // (4)
    const next = e.target instanceof HTMLInputElement && type === 'checkbox'
      ? e.target.checked
      : value                                                                           // (5)
    setValues((prev) => ({ ...prev, [name]: next }))                                    // (6)
  }

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()                                                                  // (7)
    const found = validate(values)
    setErrors(found)
    if (Object.keys(found).length === 0) onSubmit(values)                               // (8)
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      <label>
        Name
        <input name="name" value={values.name} onChange={handleChange} />
      </label>
      {errors.name && <p role="alert">{errors.name}</p>}

      <label>
        Email
        <input name="email" type="email" value={values.email} onChange={handleChange} />
      </label>
      {errors.email && <p role="alert">{errors.email}</p>}

      <label>
        Country
        <select name="country" value={values.country} onChange={handleChange}>
          <option value="PT">Portugal</option>
          <option value="DE">Germany</option>
        </select>
      </label>

      <label>
        <input name="giftWrap" type="checkbox" checked={values.giftWrap} onChange={handleChange} />
        Gift wrap
      </label>

      <label>
        Note
        <textarea name="note" value={values.note} onChange={handleChange} />
      </label>

      <button type="submit">Place order</button>
    </form>
  )
}

Here is what each numbered line does.

  1. validate is a plain function. It takes the values and returns an object of error messages. A field that is fine has no entry. Partial<Record<keyof CheckoutValues, string>> is TypeScript for "an object whose keys can only be our field names, each holding a string, and any of them can be missing".
  2. One state object for the whole form, instead of five separate useState calls. Every field's value lives here.
  3. A second piece of state holds the error messages. It is separate because errors only appear after a submit attempt.
  4. event.target is the field that changed. We read its name attribute, its type and its value.
  5. A checkbox is the odd one. Its answer is not in value but in checked (true or false). So we check what kind of field it is. Text boxes, selects and text areas all use value.
  6. One handler for every field. [name]: next is a computed key. If name is "email", this line means { ...prev, email: next }. We copy all the old values with ...prev and replace the one that changed. This is exactly the "never change, always replace" rule from page 6.4.2.
  7. A browser form reloads the page by default. preventDefault() stops that.
  8. We only call onSubmit when there are no errors. Object.keys(found).length === 0 means "the error object is empty".

In the JSX, every field follows the same pattern. The field gets a name, a value (or checked) taken from state, and onChange={handleChange}. This is the controlled input from page 6.4.2, repeated for each field. The label wraps the field so that clicking the text focuses the box. The noValidate stops the browser from showing its own pop-up messages, so ours are shown instead.

When the form is submitted with an empty name, errors becomes { name: 'Please enter your name.', email: ... }, React re-renders, and the two <p role="alert"> lines appear under the fields. The role="alert" tells screen readers to announce them.

This works, and for a small form it is exactly what you should write. But look at how much you had to write by hand: the state, the one-size handler, the validation function, the error state, and the glue between them. For a form with fifteen fields, nested lists of items, and rules like "the end date must be after the start date", this grows painful. Pages 6.4.13 and 6.4.14 show the two libraries that remove almost all of it. You needed to see the hand-written version first, so you know what they are doing for you.

4. Loading data from a server, by hand ​

Until now the products were written inside the code. In a real shop, they live on a server. Your page asks for them over the network, and the answer arrives later. This is the first time something happens outside your component, and React needs a place to run it. That place is useEffect.

Why not call fetch directly inside the component? ​

Remember: React calls your component function whenever it needs to render. If the function itself sent a network request, every render would send another one. And then the answer would call setState, which renders again, which sends another request. That is an endless loop. So the rule is: a component function must only work out the JSX. Anything else belongs in an effect.

useEffect says: "after the screen has been drawn, run this code. Then run it again only when these values change." A full explanation is in Chapter 6.4.5. For now, you need only the shape:

tsx
useEffect(() => {
  // the code to run after drawing
  return () => {
    // optional: tidy up before the next run, or when the component leaves
  }
}, [a, b])   // run again only when a or b changes

Three situations, one variable ​

When you ask a server for data, the page is always in exactly one of three situations: waiting, failed, or done. So we store one variable that says which one it is. This is shown in the figure.

Loadingshow a spinneror a skeletonSuccessshow the dataor "nothing here"Errorsay what went wrongoffer Try againanswer arrivesrequest failsTry again: back to LoadingIn codestatus: 'loading'| 'success' | 'error'one variable, one state
Loading data is never just "data or no data". The screen is always in one of these situations, and each needs its own picture. A try-again button moves the page from error back to loading.

Each of the three needs its own picture for the customer. Waiting shows a spinner. A failure says what went wrong and offers Try again. Success shows the data. A page that only handles success shows a blank screen while waiting, and a blank screen forever when something breaks.

In TypeScript, a type that is "one of these shapes" is a union. This is what it looks like for our case:

tsx
type LoadState =
  | { status: 'loading' }
  | { status: 'error'; message: string }
  | { status: 'success'; products: Product[] }

Only the success shape has products, and only the error shape has message. TypeScript will not let you read state.products until you have checked that state.status === 'success'. That removes a whole family of "undefined is not an object" crashes.

The complete component ​

tsx
import { useEffect, useState } from 'react'

function CategoryProducts({ category }: { category: string }) {
  const [state, setState] = useState<LoadState>({ status: 'loading' })

  useEffect(() => {
    let ignore = false                                                        // (1)
    setState({ status: 'loading' })                                           // (2)

    fetch(`/api/products?category=${encodeURIComponent(category)}`)           // (3)
      .then((res) => {
        if (!res.ok) throw new Error(`The server answered ${res.status}`)     // (4)
        return res.json() as Promise<Product[]>
      })
      .then((products) => {
        if (!ignore) setState({ status: 'success', products })                // (5)
      })
      .catch((err: Error) => {
        if (!ignore) setState({ status: 'error', message: err.message })
      })

    return () => {
      ignore = true                                                           // (6)
    }
  }, [category])                                                              // (7)

  if (state.status === 'loading') return <p>Loading products…</p>
  if (state.status === 'error') return <p role="alert">Could not load: {state.message}</p>
  if (state.products.length === 0) return <p>No products in this category.</p>

  return (
    <ul>
      {state.products.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  )
}
  1. A flag, ignore, that starts as false. It will be explained at (6). It is a normal variable that lives inside this one run of the effect.
  2. Each time the category changes, we go back to the "loading" situation, so the old category's products are not shown under the new heading.
  3. fetch sends the request. encodeURIComponent makes the category safe to put in a web address (so that home & garden does not break the URL).
  4. fetch does not throw on a 404 or 500. It only fails when the network itself fails. That surprises almost everyone. So we check res.ok ourselves and throw an error, which jumps to .catch.
  5. When the data arrives, store it, but only if ignore is still false.
  6. The function we return is the cleanup. React runs it before it runs the effect again, and when the component leaves the screen. It sets ignore = true. The next point explains why that matters.
  7. The dependency array. It lists every outside value the effect reads. category is read, so it is listed. When category changes, React runs the cleanup, then runs the effect again with the new value. With an empty list [], the effect runs once after the first render.

The three if lines at the bottom are "Way 3" from section 2: return early for each situation.

The bug that ignore prevents ​

Say the customer clicks "Kitchen", then quickly clicks "Garden". Two requests are now in the air. The Kitchen answer is slow. The Garden answer is fast. The Garden answer arrives first, so the page shows Garden products. Then the slow Kitchen answer arrives and overwrites them. The heading says Garden, but the list shows Kitchen things. This is called a race condition: two things race, and the loser can win.

We ran this with a slow first request and a fast second one:

text
without the ignore flag → screen shows: result for slow   (wrong: the customer chose "fast")
with the ignore flag    → screen shows: result for fast   (right)

The flag fixes it like this. When the category changes, React runs the cleanup of the old effect, which sets that old run's ignore to true. So when the slow Kitchen answer finally arrives, its own ignore is true and it throws the answer away.

"Why did my request run twice?" ​

In development, React's StrictMode (which your project template turns on) runs every effect twice on purpose. It mounts, cleans up, and mounts again. This catches code that forgets its cleanup. We measured two requests for one mount. It does not happen in the production build. If your effect works correctly with the cleanup above, the double run is harmless.

What the hand-written version cannot do ​

This code works. But think about what a real shop needs on top of it:

  • If the customer goes to another page and comes back, show the products instantly from memory and refresh them quietly.
  • If two components need the same products, send one request, not two.
  • Try again automatically when the network blinks.
  • Re-fetch when the customer comes back to the browser tab.
  • After the customer edits a product, update every screen that shows it.

Each of these is a lot of code in useEffect, and each has its own subtle bugs. That is the reason professionals do not write this by hand for server data. They use TanStack Query, which does all of it for you. You wrote the manual version on purpose: when you meet Chapters 6.4.10 and 6.4.11, you will recognise every problem it solves. And useEffect remains the right tool for things that are not server data, which Chapter 6.4.5 covers.

5. Thinking in React: how to build any screen ​

You now have every piece. The question beginners get stuck on is "where do I start, and where does each piece of state go?" The React team teaches a five-step method. We will apply it to a product page with a search box, an "in stock only" checkbox, and a list of products.

Step 1: Draw boxes around the parts of the screen ​

Look at the design, or sketch it, and draw a box around every part that has its own job. Name each box. Nouns from the design become component names.

ProductPageFilterBarSearch products☐ in stock onlyProductListProductRow · Red mug · $19.99ProductRow · Desk lamp · $45.00ProductRow · Notebook · $6.50State in ProductPagequery: stringinStockOnly: booleanpassed down as propsCalculated, not storedvisibleProducts =products filtered byquery and inStockOnlyEach rule from page 6.4.2 applied:minimum state, calculate the rest
Step 1: draw a box around every part of the screen. Step 2: give each box a name. Here ProductPage owns the two pieces of state (the search text and the in-stock checkbox) because both FilterBar and ProductList need them.

Here the page has a filter bar (the search box and the checkbox) and a list. Each row in the list is its own box too. That gives us four components: ProductPage (the whole thing), FilterBar, ProductList and ProductRow. A component should do one job. If you cannot name what a component does in a few words, it is probably two components.

Step 2: Build a version with no state at all ​

First build the screen that only shows data you give it. Pass everything down as props. Do not use useState yet. This is the easy part, and you have the tools for it from page 6.4.1.

Step 3: Find the minimum state ​

List every piece of data on the screen. For each one, ask the three questions from page 6.4.2:

DataChanges over time?Can it be calculated?So it is
The list of all productsno (comes from outside)noa prop or a constant
The text in the search boxyesnostate
Whether the checkbox is tickedyesnostate
The list that is shown after filteringyesyes, from the products and the two pieces of statecalculate it

So there are only two pieces of state: query and inStockOnly. The filtered list is worked out during every render.

Step 4: Decide which component owns each piece of state ​

For each piece of state, find every component that shows it or needs it. Then put the state in their closest shared parent. Both FilterBar (shows the text) and ProductList (filters by it) need query. Their closest parent is ProductPage. So ProductPage owns query and inStockOnly. This is the "lifting state up" move from page 6.4.2.

Step 5: Add the flow back up ​

State flows down as props. But FilterBar must be able to change the state that lives in its parent. So the parent also passes functions down, and the child calls them. React calls this "one-way data flow": values go down, requests for change go up.

Here is the complete page:

tsx
import { useState } from 'react'

type Product = { id: string; name: string; priceCents: number; inStock: boolean }

const allProducts: Product[] = [
  { id: 'p1', name: 'Red mug', priceCents: 1999, inStock: true },
  { id: 'p2', name: 'Desk lamp', priceCents: 4500, inStock: false },
  { id: 'p3', name: 'Notebook', priceCents: 650, inStock: true },
]

type FilterBarProps = {
  query: string
  inStockOnly: boolean
  onQueryChange: (query: string) => void
  onInStockOnlyChange: (value: boolean) => void
}

function FilterBar({ query, inStockOnly, onQueryChange, onInStockOnlyChange }: FilterBarProps) {   // (1)
  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <input
        value={query}
        onChange={(e) => onQueryChange(e.target.value)}                                              // (2)
        placeholder="Search products"
      />
      <label>
        <input
          type="checkbox"
          checked={inStockOnly}
          onChange={(e) => onInStockOnlyChange(e.target.checked)}
        />
        In stock only
      </label>
    </form>
  )
}

function ProductRow({ product }: { product: Product }) {
  return (
    <li>
      {product.name}: ${(product.priceCents / 100).toFixed(2)}
      {!product.inStock && <span> (sold out)</span>}
    </li>
  )
}

function ProductList({ products }: { products: Product[] }) {
  if (products.length === 0) return <p>Nothing matches your search.</p>                              // (3)
  return (
    <ul>
      {products.map((p) => (
        <ProductRow key={p.id} product={p} />
      ))}
    </ul>
  )
}

export default function ProductPage() {
  const [query, setQuery] = useState('')                                                              // (4)
  const [inStockOnly, setInStockOnly] = useState(false)

  const visibleProducts = allProducts.filter((p) => {                                                 // (5)
    if (inStockOnly && !p.inStock) return false
    return p.name.toLowerCase().includes(query.trim().toLowerCase())
  })

  return (
    <>
      <FilterBar
        query={query}
        inStockOnly={inStockOnly}
        onQueryChange={setQuery}                                                                      // (6)
        onInStockOnlyChange={setInStockOnly}
      />
      <ProductList products={visibleProducts} />
    </>
  )
}
  1. FilterBar has no state of its own. It receives the current values and two functions. Its props type says exactly what it needs, so anyone reading it knows how to use it.
  2. When the user types, FilterBar does not store anything. It calls onQueryChange with the new text, which asks the parent to change.
  3. ProductList handles the empty case itself with an early return. Think of "what if there is nothing?" for every list you draw.
  4. The only two pieces of state on the whole page, owned by the closest shared parent.
  5. The filtered list is calculated on every render from the two pieces of state and the full list. It is not stored. It can never be out of date.
  6. setQuery is itself a function that takes the new text, so we can pass it down directly as onQueryChange. No extra wrapper needed.

Trace one keystroke through it. The customer types l. The input's onChange runs and calls onQueryChange('l'), which is setQuery. ProductPage re-renders with query = 'l'. It calculates visibleProducts: only "Desk lamp" contains an l. "Red mug" has no l and "Notebook" has no l. Only "Desk lamp" does. So the list has one row. It passes that list down, and ProductList draws one ProductRow. The FilterBar also re-renders and the input shows l. This is the render loop from page 6.4.2, applied to a real screen.

The method is the same for every screen you will ever build: boxes, static version, minimum state, owner of each piece, flow back up. When a feature feels overwhelming, go back to step 1.

A warning sign for the next pages ​

Lifting state works beautifully until the state must travel through many layers. Suppose the cart lives in App, and a small "Add" button four levels deep needs it. You would pass the cart and addItem through every layer in between, even through components that do not care. This is called prop drilling, and it is what Context, Redux and Zustand solve. Chapter 6.4.6 explains the problem and the options, and Chapters 6.4.7 and 6.4.8 teach them step by step.

What the interviewer will push on ​

"Why do list items need a key, and what makes a good one?" React uses the key to match last render's items with this render's items, so each row keeps its own state and DOM. A good key is stable and unique among siblings, such as a database id. Say what goes wrong with an index key: delete the first row and the typed text stays at position 0 and now belongs to the next item. They are checking that you know the key is about identity, not just a way to silence a warning.

"What is wrong with {count && <Cart />}?" When count is 0, React draws the 0. Write count > 0 && ... or use a ternary. The common wrong answer is "nothing is drawn", which is true for false and null but not for 0.

"Controlled versus uncontrolled inputs. When would you use each?" Controlled: the value lives in React state, so you can validate or react to every keystroke. Uncontrolled: the browser holds the value and you read it when needed (through a ref or FormData). Uncontrolled is simpler and faster for big forms, and it is what React Hook Form uses internally (Chapter 6.4.14).

"How do you fetch data in a component? What can go wrong?" Inside useEffect, never in the render body. Track loading, error and success. Handle res.ok yourself, because fetch does not reject on 404 or 500. Clean up with an ignore flag or an AbortController so a slow old request cannot overwrite a newer one (the race condition). Then say the part that scores: "In real projects I would use TanStack Query, so caching, dedupe and retries are not hand-written."

"Why did my effect run twice?" StrictMode in development mounts, cleans up and mounts again to catch missing cleanups. It does not happen in production.

"Where should this state live?" The closest component that contains everything that needs it. Walk through the five steps out loud. Explain why you calculate the filtered list instead of storing it.

One thing to volunteer: mention that you derive the filtered list during render instead of keeping a second filteredProducts state. It shows you understand the "single source of truth" rule that most bugs come from breaking.

Recall

  • Lists: array.map(item => <Component key={item.id} … />). The key is the row's identity: stable, unique among siblings, from your data. Index keys break state when rows are removed or reordered. Filter and sort before map, and handle the empty list.
  • Conditions: ternary for two choices, && for something-or-nothing, early return for a whole different shape, a lookup object for many. {0 && …} draws 0, so compare with > 0. Not drawing a component destroys its state; hiding it with CSS keeps it.
  • Forms: one state object, one handleChange that uses [name]: value (and checked for checkboxes), preventDefault on submit, validate on submit and keep the errors in state. It grows painful with big forms, which is why 6.4.13 and 6.4.14 exist.
  • Loading data: never fetch in the render body. Use useEffect with a dependency array. Track one status (loading, error, success). fetch does not throw on 404 or 500, so check res.ok. Use a cleanup (ignore flag) so a slow, old response cannot overwrite a newer one. StrictMode runs the effect twice in development only. Caching, dedupe and retry are what TanStack Query adds.
  • Thinking in React: boxes → static version → minimum state → closest owner of each piece → flow functions back up. Calculate everything you can instead of storing it. Passing props through many layers is prop drilling, which Context, Redux and Zustand solve.

Self-test: What did the gift note do when the first row was deleted with an index key, and why? · Why does {items.length && …} show a zero? · Why do we write [name]: next in the form handler? · What does the cleanup function stop? · Which two pieces of state does the product page own, and why is the filtered list not one of them?

Next: 6.4.4 looks under the hood. It shows how React compares the old and new screen, how keys are used in that comparison, and what the fiber engine does. After that, 6.4.5 covers every hook in full, and the pages after it add the libraries real projects use.

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