← All courses

Production React & TypeScript

Twenty-six lessons taking you from "what is a component?" to production-grade decisions, covering everything the 140-card quiz tests. Each ends with the key point the questions ask.

New to this? Start at Part 0 — six plain-English lessons on what React, TypeScript, Node and SQL each are and how they fit together. No prior experience assumed.

Already working with this stack? Skip to Part 1. From there it assumes you can write React and SQL, and it's about the decisions that separate code that works from code that survives production.

Part 0 Start here — no experience needed

0.1 What are we actually building?

"Full stack" means the whole of a web application, and it's really just three jobs:

Ordering a takeaway is the same shape: the menu and your basket are the front end, the restaurant deciding whether they can cook it is the back end, and the written-down order is the database.

TypeScript and GraphQL aren't extra layers — they're aids. TypeScript catches mistakes before you run the code, and GraphQL is one particular way for the front end to ask the back end for data.

Key point: front end (browser) → back end (server) → database. Everything in this course is one of those three, or the glue between them.

0.2 React: components, props and state

React builds a page out of components — reusable pieces you define once and use many times. A component is just a function that returns what should appear:

function Greeting() {
  return <p>Hello there</p>
}

Props are the inputs you pass in, like arguments to any function:

function Greeting({ name }) {
  return <p>Hello {name}</p>
}

<Greeting name="Sam" />   →   Hello Sam

State is information that changes while the page is open — a counter, a typed search box, whether a menu is open. The crucial idea: when state changes, React automatically redraws whatever displayed it. You never update the page by hand; you change the state and React works out what to redraw.

const [count, setCount] = useState(0)
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>

That automatic redrawing is React's whole reason to exist — and once you understand it, Part 1 (which is largely about controlling when redraws happen) makes sense.

Key point: components are functions returning UI, props are their inputs, state is data that changes — and changing state redraws the screen automatically.

0.3 Why TypeScript

JavaScript lets you do this quite happily, then fail at 3am in production:

JavaScript user.emial — a typo. Runs fine, silently gives you undefined, breaks something later.
TypeScript Same typo is a red underline in your editor, before you ever run it.

TypeScript is JavaScript plus types — labels saying what kind of value something is:

let name: string = "Sam"      // must be text
let age: number = 14           // must be a number

type User = {                  // an object with exactly these fields
  name: string
  age: number
  email?: string               // the ? means optional
}

One thing that trips up every beginner: types vanish when the code runs. They're checked as you write, then stripped out. So they protect you from your own mistakes, but they can't check data arriving from the internet — which is exactly why Lesson 19 talks about validating input separately.

Key point: types catch mistakes while you write, then disappear at runtime. They protect your code, not your data.

0.4 What Node.js is for

JavaScript was invented to run in browsers. Node.js lets you run it outside a browser — on a server — so you can write both halves of your app in one language.

The back end's job is everything the browser can't be trusted with: checking who you are, deciding what you're allowed to see, talking to the database, keeping secrets. Anyone can edit what runs in their own browser, so every real rule has to live on the server.

The one thing to understand early is that Node does its work on a single thread — one worker handling everyone. It stays fast because it never sits and waits: when it asks the database for something, it goes and serves someone else until the answer arrives.

The catch is the other side of that coin: if you give that one worker a slow calculation to do, everyone waits. Lessons 6–8 are essentially about that single fact and how to work with it.

Key point: Node runs JavaScript on the server, on one thread that juggles waiting well and heavy calculation badly.

0.5 Databases and SQL in ten minutes

A database stores information permanently, in tables — like spreadsheets. A table has columns (the fields) and rows (the records):

users
 id │ name  │ email
────┼───────┼──────────────
  1 │ Sam   │ sam@x.com
  2 │ Alex  │ alex@x.com

SQL is how you talk to it, and it reads close to English:

SELECT name FROM users WHERE id = 1;        -- read
INSERT INTO users (name) VALUES ('Ana');   -- create
UPDATE users SET name = 'Ana B' WHERE id = 3;
DELETE FROM users WHERE id = 3;

Two ideas the later lessons lean on heavily:

Key point: tables of rows and columns, SQL to read and change them, indexes to find things fast, transactions to keep changes all-or-nothing.

0.6 How a request actually flows

Putting it together — you click "Save" on a profile page:

  1. React handles the click and sends the new details to your server (an API request — one program asking another for something).
  2. Node receives it and checks: are you logged in? Is this your profile? Is the email actually a valid email?
  3. Node sends SQL to PostgreSQL, which saves it and confirms.
  4. Node replies to the browser. React updates state, and the page redraws itself.

Every lesson that follows lives at one of those steps. Rendering and state are step 1 and 4; the event loop and streams are step 2; GraphQL is how step 1 asks step 2 for things; indexes and transactions are step 3; caching and deploys are about the whole path.

How to use this course: you don't need to master a part before moving on. Read a part, take that topic's quiz using the topic filter, and let the explanations fill the gaps — every question explains the rule behind its answer.

Key point: browser asks → server checks and decides → database stores → browser updates. Every topic in this course sits at one of those four steps.

Part 1 React & TypeScript

1 Modelling state you can't get wrong

Most React bugs are impossible states that the type system permitted. Compare:

Weak { loading: boolean; error?: string; data?: User } — eight combinations, of which about three are meaningful. Nothing stops loading: true with an error and data.
Strong | { status: 'loading' } | { status: 'error'; error: string } | { status: 'ok'; data: User }

This is a discriminated union: a shared literal field (the discriminant) whose value tells TypeScript exactly which member you have. Once you write if (s.status === 'error'), the compiler narrows — inside that branch s.error exists and is a string, with no optional chaining and no defensive checks.

How to apply it: when you find yourself writing data?.thing ?? fallback repeatedly, or a comment explaining which combinations are valid, that's the signal to reach for a union.

Two TypeScript tools that pay for themselves here: satisfies, which checks a value against a type while keeping literal precision, and Omit<Props,'x'> & { x: NewType } for wrapping a third-party component and changing one prop without redeclaring the rest.

Key point: make impossible states unrepresentable. Discriminated unions narrow on the discriminant, so valid data is the only data you can construct.

2 Render performance and the memo trap

memo does a shallow comparison of props. That single fact explains most failed optimisations:

<Row item={item} onPick={() => pick(item.id)} />   // memo never helps

The inline arrow is a new reference every render, so the comparison always fails. Same for style={{...}} and inline arrays.

useCallback and useMemo exist to stabilise identity or avoid genuinely expensive work — not to make functions faster. Both cost something: storing the value, storing the dependency array, and comparing deps every render. Wrapping a string concatenation costs more than recomputing it.

The rule: memoise when something downstream compares the identity — a memoised child, or another hook's dependency array. Otherwise don't.

Context has the same failure. value={{ user, logout }} is a fresh object each render, so every consumer re-renders regardless of what changed. Memoise the value, or split volatile and stable data into separate contexts.

How to apply it: profile before optimising. React DevTools' Profiler tells you which commits were expensive and which props changed. Blanket memoisation is guesswork that adds cost and hides the real cause.

Key point: memo compares shallowly, so unstable props defeat it. Memoise for identity, not for speed — and profile before you do either.

3 Effects, races and cleanup

This looks fine and is broken:

useEffect(() => {
  fetch(url).then(r => r.json()).then(setData)
}, [url])

If url changes quickly, request 1 can resolve after request 2 and overwrite it with stale data. Fix with an ignore flag in the cleanup, or an AbortController.

Cleanup is not optional politeness. React 18's StrictMode deliberately mounts, unmounts and remounts in development precisely to expose subscriptions, timers and listeners you never tore down. Code that survives the double-invoke behaves correctly when React remounts a tree for real.

Two more traps worth internalising. Stale closures: setN(n+1); setN(n+1) increments by one, because both calls close over the same n — use the updater form when the next value depends on the previous. And keys: an array index as key makes component state follow the position rather than the item, so deleting a row leaves focus and input values attached to the wrong data.

Finally, useRef versus useState: refs persist without triggering a render. Timer ids and previous values belong in refs; anything the UI displays belongs in state.

Key point: async effects need cleanup or they race. StrictMode's double-invoke is a bug detector, not a bug.

4 Suspense, boundaries and streaming

Two boundary types, two jobs. Error boundaries catch errors during rendering, lifecycle methods and constructors below them — but not in event handlers, async code, or SSR. An error in an onClick is ordinary JavaScript; use try/catch. They must be classes, because React never shipped a hook for catching render errors.

Suspense is the same idea for pending states: render a fallback while any descendant suspends. It doesn't fetch, cache, or handle errors — it reacts to a component suspending.

That primitive is what makes streaming SSR work. Classic SSR must finish every query before sending a byte, so time-to-first-byte is hostage to the slowest one. Streaming sends the shell immediately and flushes each Suspense boundary as its data resolves.

Related: useTransition marks an update low priority so React can interrupt it for urgent work like typing. It's about priority, not timing or threading.

Watch for hydration mismatches: Date.now(), Math.random(), locale formatting and browser checks during render make client output differ from server output, forcing React to throw away that subtree. Keep render deterministic; move browser-dependent output into an effect.

Key point: error boundaries catch render-phase failures only; Suspense handles pending states and enables streaming SSR.

5 Testing and accessibility together

React Testing Library's guiding principle is to query the way a user finds things. That makes accessibility and testability the same problem:

Good getByRole('button', { name: 'Save' }) — fails if you break the accessible name or use a div instead of a button.
Weak getByTestId('save-btn') — passes happily while the component is unusable with a keyboard.

Query selection matters: getBy throws immediately if absent, findBy returns a promise and retries (use after triggering a fetch), and queryBy returns null for asserting absence.

On the accessibility side, the highest-value habit is using real elements. <div onClick> has no role, no tab stop and no Enter/Space activation — recreating all that with tabIndex, role and key handlers is strictly more work than <button>. And remember aria-label overrides visible content in the accessible-name calculation, which is why a stale label silently misrepresents a changed icon.

Key point: query by role and name. Tests that find elements the way users do catch accessibility regressions for free.

Part 2 Node.js

6 The event loop, precisely

Ordering questions are really questions about queues. Given all four scheduled together:

process.nextTick(cb)   // drains first, before promises
Promise.resolve().then(cb)  // microtask queue, next
setTimeout(cb, 0)      // timers phase
setImmediate(cb)       // check phase

nextTick drains completely before promise microtasks, and both run before the loop continues to any phase. From the main module, timer vs check ordering is genuinely non-deterministic — it depends how long startup took. Inside an I/O callback, setImmediate always wins.

The practical consequence: recursive nextTick starves the loop. It never yields, so timers and sockets never fire and the process appears hung. setImmediate schedules one callback per iteration, leaving room for I/O.

The deeper point is that there is one main thread. A 50MB JSON.parse or a heavy crypto operation blocks every concurrent request — a thread-per-request server would isolate it. That's what worker threads are for: CPU-bound work. They add nothing to I/O, which is already non-blocking. Cluster is the different tool — separate processes sharing a listening socket, for scaling a stateless server across cores.

Key point: nextTick → microtasks → loop phases. One thread means blocking work stalls everything; workers are for CPU, cluster is for cores.

7 Streams and backpressure

Backpressure is the signal that a destination can't keep up. writable.write() returns false when its buffer exceeds highWaterMark. Ignore that return value and you push data into memory faster than it drains — the classic cause of a Node process ballooning to gigabytes:

Broken readable.on('data', c => writable.write(c)) — manual piping with no pause.
Correct await pipeline(readable, transform, writable)

Prefer stream.pipeline() over chained .pipe(). With .pipe(), an error mid-chain leaves the other streams open and undestroyed — a well-known file-descriptor leak. pipeline propagates errors, destroys the whole chain, and gives you one error path.

The general principle: memory use should be constant with respect to input size. If your service reads a whole upload into a Buffer before processing it, its capacity is set by the largest file anyone sends.

Key point: honour backpressure or buffer unboundedly. Use pipeline, not chained pipes, so errors clean up the whole chain.

8 Concurrency without collapse

Three patterns, three different mistakes.

Accidentally sequential. for (const id of ids) results.push(await fetch(id)) is correct but takes the sum of every call. If they're independent, await Promise.all(ids.map(fetch)) takes the longest.

Unbounded parallel. Promise.all over 10,000 ids launches 10,000 simultaneous requests, exhausting sockets, file handles or the database pool. Use a concurrency limiter so you saturate throughput without collapsing the downstream service.

All-or-nothing. Promise.all rejects on the first failure — right when any failure invalidates the operation. When partial success is acceptable, Promise.allSettled gives you every outcome.

Put together, the shape for an endpoint calling three services: concurrent, each with its own timeout so one dependency can't dictate your p99, and graceful degradation when a non-critical one fails.

Key point: parallelise independent work, bound the concurrency, and time-bound every external call.

9 Auth: tokens vs sessions

A signed JWT is not encrypted. The payload is base64url — anyone holding it can read it. Signing proves integrity and origin, not confidentiality, so it carries an opaque user id and never a secret.

The real trade-off is revocation. A JWT is valid until it expires because verification is local — that's the entire scaling benefit, no shared session store. Immediate logout or ban therefore requires a denylist, or short expiry plus refresh tokens, which reintroduces the state you were avoiding.

Storage: anything reachable from JavaScript is reachable by injected JavaScript, so localStorage is a poor choice. An httpOnly; Secure; SameSite cookie removes the token from script access entirely, at the cost of needing CSRF protection.

Rate limiting has one non-obvious failure: in-memory counters are per-process, so ten instances allow ten times your intended limit. It needs shared storage. And fixed windows let a client send a full quota either side of a boundary — sliding-window or token-bucket smooths that out.

Key point: JWTs are readable and unrevokable by design; that's the price of stateless verification. Rate limiters need shared state.

10 Production hygiene

Structured logging. log.info({ userId, durationMs }, 'request complete') can be filtered and aggregated; an interpolated string forces every consumer to reverse-engineer your format. Add a correlation id at the edge and propagate it — without one, concurrent requests interleave and you can't reconstruct a single journey. AsyncLocalStorage lets a logger deep in the stack read it without threading a context object through ten layers.

Graceful shutdown on SIGTERM: stop accepting connections, finish in-flight requests, close pools, exit — with a forced-exit timer, because a websocket or long poll may never end on its own and would keep the process alive through the whole deploy.

Crash properly. On uncaughtException, log and exit. The stack unwound from an unknown point, so locks and transactions may be inconsistent; continuing risks silent corruption.

Validate at the boundary. TypeScript types vanish at runtime, so req.body as CreateUser is a promise you made to yourself. A schema parse validates and produces the type.

Health checks: keep liveness trivial. A liveness probe that queries the database will restart every pod during a transient DB blip — exactly when you least want it. Dependency checks belong in readiness.

Key point: log structured with a correlation id, drain on SIGTERM with a deadline, exit on uncaught exceptions, and parse input at the edge.

Part 3 GraphQL

11 Schema design as a contract

GraphQL's advantage over REST is removing over- and under-fetching: the client states exactly which fields it needs, in one round trip. The cost is that caching and query-cost control become your problem.

The most consequential design rule: the schema models your domain, not your tables. Exposing a raw column set couples the public API to storage, so splitting a table becomes a breaking change for every consumer.

Non-null is a promise with teeth. If a non-nullable resolver returns null, the null propagates upward to the nearest nullable parent — and if every ancestor is non-null, data itself becomes null. Over-using ! makes an API brittle.

Because GraphQL is versionless, evolution is additive: @deprecated fields keep working while you watch usage fall to zero. Custom scalars like DateTime centralise parsing and validation. Mutations return the modified object so clients can patch their normalised cache without a refetch, and they execute serially — unlike query fields, which resolve in parallel.

Key point: model the domain, not the database. Nullability is a contract, and evolution is additive rather than versioned.

12 N+1 and DataLoader

Query 100 posts, and a perfectly reasonable-looking author resolver runs 100 separate user lookups. 1 + N queries. It's the most common GraphQL performance failure precisely because each resolver is innocent in isolation.

DataLoader fixes it by batching: each resolver still asks for one author, but the loader collects those keys within a tick and calls your batch function once with all of them — WHERE id IN (...).

Two details that cause real bugs:

Key point: batch per-item lookups with a per-request DataLoader, and return results in key order.

13 Pagination

OFFSET 100000 makes the database walk and discard 100,000 rows. Worse, a row inserted at the top means page 2 repeats an item from page 1.

Cursor pagination says "after this exact record" — indexable and stable under concurrent writes. What you give up is jumping to an arbitrary page number and a cheap exact count. That's fine for infinite scroll and APIs, and a poor fit for numbered-page UIs.

In the Relay connection spec, the edge exists separately from the node so there's somewhere to put the cursor and per-relationship data: a TeamMemberEdge carries role and joinedAt — facts about the membership, not the user.

Pair this with result limits. Tell clients the cap. A connection silently returning the first 50 of 4,000 invites confidently wrong conclusions.

Key point: cursors are stable and indexable; offsets scan and shift. Edges carry relationship data, nodes carry entity data.

14 Errors, security and federation

Model expected failures as types. union LoginResult = LoginSuccess | InvalidCredentials | AccountLocked forces the client to handle each branch, leaving the top-level errors array for genuinely exceptional problems. "Not found" for a single item is a null from a nullable field, not an exception — GraphQL responses are 200 regardless.

Mask internal errors. Raw driver messages leak table names, column names and versions. Log detail server-side with a correlation id; return a generic message plus a code.

Security is different from REST's. Cyclic relationships let a tiny query nest almost indefinitely, so depth limits and complexity scoring are necessary. Introspection publishes your entire schema — invaluable in development, free reconnaissance in production. Persisted queries address both: clients reference pre-registered operations by hash, turning an arbitrary-query endpoint into an allowlist and restoring GET-based CDN caching.

Authorisation must be enforced per field at execution time, with the caller's identity. Any client can request any field the schema exposes, so client-side omission is not a control.

Federation lets subgraphs own parts of a type. type User @key(fields: "id") means the Users subgraph owns core fields while Reviews contributes User.reviews; __resolveReference hydrates a key stub into a full object — and is a prime N+1 site needing a loader.

Key point: type your expected errors, mask internal ones, limit query cost, and authorise per field at runtime.

Part 4 PostgreSQL

15 Index design

A composite index is usable left to right. Think of a phone book sorted by surname then first name: you can find all Smiths instantly, but not everyone called John.

So with an index on (tenant_id, created_at):

Uses it WHERE tenant_id = 5 ORDER BY created_at DESC — tenant fixed by equality, so rows are already ordered by date within it. The sort is free.
Can't WHERE created_at > now() - interval '1 day' — the leading column is absent.

The design rule: equality columns first, then the range or sort column.

Beyond that: an index-only scan needs every required column in the index and an up-to-date visibility map — another reason vacuuming matters. A partial index (WHERE deleted_at IS NULL) can be a twentieth the size on a mostly-archived table. And a function makes a predicate non-sargable: WHERE lower(email) = $1 can't use a plain index on email, because the index stores raw values — use an expression index or citext.

Key point: indexes are usable on a left prefix. Equality first, then range/sort; functions in predicates need matching expression indexes.

16 Reading a query plan

EXPLAIN shows the estimated plan. EXPLAIN ANALYZE actually runs it and reports real timings and row counts — wrap writes in a transaction you roll back.

The whole diagnostic technique is one comparison: estimated rows versus actual rows. A plan expecting 10 and getting 500,000 explains every bad join choice downstream. Fix the estimate — ANALYZE the table, raise the statistics target, add extended statistics for correlated columns — and the plan usually fixes itself.

This also explains the question that surprises people: why did Postgres ignore my index? It didn't ignore it, it costed it. Above roughly 5–20% selectivity, hopping to scattered heap pages costs more than reading sequentially. If that estimate is wrong, the culprit is usually stale statistics.

Guard against pathological queries with statement_timeout on the application role. One runaway query can pin a connection, block vacuum and cascade into a site-wide stall; a timeout converts that into one failed request.

Key point: compare estimated to actual rows. A sequential scan is a costing decision, not a bug — usually a statistics problem.

17 Transactions and isolation

Postgres defaults to READ COMMITTED, where each statement sees data committed before that statement began. The snapshot is per statement, not per transaction — so two identical SELECTs in one transaction can differ.

That's why this is a bug:

SELECT balance FROM accounts WHERE id = 1;   -- 500
-- other transaction does the same
UPDATE accounts SET balance = 400 WHERE id = 1;

Two concurrent deductions, one survives — a lost update. Three fixes: do it in one statement (SET balance = balance - 100), lock the row with SELECT ... FOR UPDATE, or use SERIALIZABLE.

REPEATABLE READ gives one snapshot for the whole transaction. SERIALIZABLE detects dangerous read/write patterns and aborts one transaction with SQLSTATE 40001 — which means it is only a correctness guarantee if your application actually retries. Without the retry loop you've just made it fail more often.

Deadlocks happen when two transactions acquire locks in different orders. Postgres detects the cycle and aborts one; the durable fix is a consistent acquisition order, commonly sorting ids before updating.

Key point: read-modify-write is unsafe by default. Higher isolation means handling serialization failures with retries.

18 Migrations and pooling

Migrations must be safe against running code. A straight RENAME COLUMN breaks every running instance the instant it commits. The expand-and-contract pattern spans several releases: add the new column, write to both, backfill, migrate readers, drop the old one.

Use CREATE INDEX CONCURRENTLY in production — a normal CREATE INDEX blocks writes for the whole build. Since Postgres 11, ADD COLUMN ... NOT NULL DEFAULT is a fast catalogue change rather than a full table rewrite. Prefer forward-only migrations: a bad migration is fixed by a new one, not by a down script nobody has tested against production data.

Pooling matters more here than elsewhere because Postgres forks an OS process per connection, with real memory cost. Pool sizes multiply by instance count — 20 per instance × 10 instances against max_connections = 100 means refused connections, a classic autoscaling outage.

PgBouncer in transaction mode multiplexes aggressively, but breaks session-scoped features: prepared statements, session variables, advisory locks, LISTEN/NOTIFY.

Run migrations as a separate deploy step, not on app boot — ten pods starting at once means ten concurrent migration runs.

Key point: expand and contract so old and new code coexist; size pools against total instances, and know what transaction pooling breaks.

Part 5 Full-stack integration

19 End-to-end type safety

The goal is a broken contract becoming a build failure. Hand-written duplicate interfaces drift silently; one source of truth means the compiler notices.

Three routes, different trade-offs. tRPC has the client import the router's type directly — inference flows across the boundary with no codegen step, and nothing ships to the browser. That suits a TypeScript monorepo and does nothing for a Swift client. GraphQL Code Generator derives types from the schema and your operations, so removing a field server-side fails the client build. OpenAPI plays the same role for REST.

All of them still need runtime validation at the boundary, because types are erased. Derive the type from the schema — z.infer<typeof userSchema> — so validation and type cannot disagree.

This is much of why monorepos suit full-stack TypeScript: the contract change and its consumers land in one atomic commit, and CI checks the whole system.

Key point: one source of truth for the contract, plus a runtime parse at the boundary — types alone never validate anything.

20 Caching, deploys and observability

Caching. The cheapest work is work you don't do: browser → CDN → application/Redis → database, each step back toward origin costing latency and load. Content-hashed filenames (app.a3f9c1.js) let you cache assets immutably forever. Watch for stampede — one popular key expiring turns into thousands of simultaneous origin queries — and remember that clearing a shared cache leaves per-instance local copies stale.

Deploys. Zero-downtime means old and new versions run simultaneously against the same schema, so every change must be backward compatible for one release. Distinguish your probes: liveness asks "restart this?", readiness asks "send traffic now?" — conflating them turns a DB blip into a full restart storm. Feature flags decouple releasing code from enabling behaviour.

Observability. Metrics tell you something is wrong, traces tell you where in a distributed call path, logs tell you what happened in that step. Measure p95/p99, not the mean — a 100ms average can hide 5% of users waiting three seconds.

Safety. Secrets come from the environment or a secret manager; git history is permanent, so a committed secret is compromised even after deletion. Mind client-exposed prefixes like NEXT_PUBLIC_. Give mutating endpoints an idempotency key so a retry after a lost response doesn't double-charge. And remember CORS is enforced by the browser — it stops scripts, not curl.

Key point: cache close to the user, keep versions compatible across a rolling deploy, and measure the tail rather than the average.

▶ Going further

At this level the primary sources beat tutorials — but these help:

  • The official React docs, Node API docs and PostgreSQL manual — the Postgres manual in particular is unusually well written, and the indexing and MVCC chapters are worth reading end to end.
  • Corey Schafer and freeCodeCamp for long-form course material.
  • Use EXPLAIN ANALYZE on your own slow queries — one afternoon reading real plans teaches more than any article.

That's the course. Now test it:

Take the React & TypeScript quiz →

Pick React & TypeScript · Full Stack under Pro Dev — 140 questions, and you can filter to one topic at a time.