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:
- The front end — what runs in your browser. The buttons, forms and lists you can see. That's React's job here.
- The back end — a program running on a server somewhere, which the front end talks to over the internet. It decides what's allowed and does the real work. That's Node.js.
- The database — where information is stored so it's still there tomorrow. That's PostgreSQL.
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.
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.
0.3 Why TypeScript
JavaScript lets you do this quite happily, then fail at 3am in production:
user.emial — a typo. Runs fine, silently gives you undefined, breaks something later.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.
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.
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:
- An index is like the index at the back of a book. Without one, the database reads every row to find what you asked for. With 10 rows that's instant; with 10 million it's your outage. That's Lesson 15.
- A transaction groups several changes so they all happen or none do — moving money between accounts must never do half. That's Lesson 17.
0.6 How a request actually flows
Putting it together — you click "Save" on a profile page:
- React handles the click and sends the new details to your server (an API request — one program asking another for something).
- Node receives it and checks: are you logged in? Is this your profile? Is the email actually a valid email?
- Node sends SQL to PostgreSQL, which saves it and confirms.
- 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.
Part 1 React & TypeScript
1 Modelling state you can't get wrong
Most React bugs are impossible states that the type system permitted. Compare:
{ loading: boolean; error?: string; data?: User } — eight combinations, of which about three are meaningful. Nothing stops loading: true with an error and data.| { 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.
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.
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.
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.
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:
getByRole('button', { name: 'Save' }) — fails if you break the accessible name or use a div instead of a button.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.
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.
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:
readable.on('data', c => writable.write(c)) — manual piping with no pause.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.
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.
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.
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.
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.
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:
- Per request, always. A shared global loader's cache can hand user B data that user A was authorised to see, and serves stale values indefinitely.
- Return keys in order. DataLoader matches results positionally, so
the batch function must return an array the same length as the keys, in the same
order, with null for misses. A SQL
INreturns arbitrary order and omits misses — forgetting to re-map misattributes data to the wrong entity.
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.
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.
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):
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.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.
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.
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.
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.
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.
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.
▶ 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 ANALYZEon your own slow queries — one afternoon reading real plans teaches more than any article.