HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 6“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Advanced React, State Management and Data Fetching
After lesson 5, TechLearningPro's lesson outline had one owner and a test that clicked a checkbox by name.
Course progress0%
Focus
18 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 06 · Full-Stack Engineering Foundations
Lesson Overview
After lesson 5, TechLearningPro's lesson outline had one owner and a test that clicked a checkbox by name. The next bug was quieter. The player fetched progress in an effect, the learner navigated to another lesson before the response returned, and the late response wrote the previous lesson's checkmarks into the new screen. A second bug stored the same payload in a context, a module-level variable, and a useState copy, so a refetch updated one of them. The Monday board said the learner was finished. The player said they were not.
This lesson separates three kinds of state and gives server state a cache with cancellation, explicit failure, and a query key that includes the resource identity. Local UI state stays in useState or useReducer. Shared UI state that is not server data can use context or a small store. Server state — outlines, completion, notes that must survive a reload — is fetched, cached, and invalidated. The React course covers more hook surface. Here the outcome is a player that survives a slow network and a fast click.
Assumptions, labeled as lesson constraints rather than a vendor contract:
React 18 client components. Examples use useState, useReducer, useEffect, useContext, and useTransition.
Reads go through fetch and AbortController, which are web platform APIs. The sample URL is a relative /api/lessons/ path your own app serves. This lesson does not invent a third-party progress vendor.
Optional cache: TanStack Query v5 (@tanstack/react-query) with useQuery, useMutation, queryKey, queryFn, and QueryClientProvider. Confirm the major version in package.json. v5 uses isPending and gcTime. v4 used isLoading for the same idle case and cacheTime. Do not mix the names.
The handler behind /api/lessons/:id is specified only as "returns JSON or an error status." Lesson 7 shows a Next.js route handler. Lesson 9 owns a Node server. Authorization is a server duty even though the UI shows loading and error states.
Model output is not a second source of completion. If a later lesson streams tokens, that stream is ephemeral client state keyed by a request id, rendered as text, and never written as progress unless the learner confirms and the server accepts it.
Learning Objectives
By the end of this lesson you will be able to:
Classify a piece of data as local UI state, shared client state, or server state, and say where it lives.
Replace boolean soup with useReducer when a player interaction has several legal transitions.
Use context to pass a stable dependency such as a query client or a theme, and explain the re-render cost of a fast-changing context value.
Fetch with AbortController so a slow response cannot land on the wrong lesson.
Model loading, success, empty, and error without a boolean pair that can both be true.
Use TanStack Query v5 for cached reads and mutations, including a query key that contains the lesson id.
Invalidate or update a query after a successful mutation instead of keeping a shadow copy in useState.
Keep authorization on the server and treat a 401 or 403 as a UI state, not as a prompt to hide the real error in the console only.
Avoid putting secrets, raw model HTML, or one tenant's payload under another tenant's cache key.
Test the success path, the aborted path, and the error path without a live backend.
Decide when a global store would add cost without removing a bug.
Leave a seam the App Router lesson can replace: presentational components still receive props.
Prerequisites
Lesson 5's player: typed OutlineItem, controlled inputs, immutable updates, tests by role. If the outline still mutates objects, fix that first.
Ability to read a JSON response and narrow it with a type guard before it enters React state. The TypeScript lesson is the language background.
A local dev server or a test mock. You do not need a production database.
If a component both fetches and renders rows, split it before adding a library. The library will not invent the boundary you skipped.
Detailed Core Concepts
Three kinds of state
Local UI state is meaningful only in one component and dies with it: whether a menu is open, which tab is highlighted, a note draft that is not saved. useState is enough. useReducer is better when the next state depends on the event and several fields must change together, because impossible combinations stay out of the reducer.
Shared client state is UI data many components read that is still not the server's record: theme, the id of the open dialog, a playback rate. React context works when the value changes rarely. A store such as Zustand (create from zustand) or Redux Toolkit (configureStore, createSlice) works when many distant writers update client-only state and you want subscriptions. Neither store is the system of record for completion.
Server state is data another process owns. It can be stale, missing, or forbidden. It needs a key, a fetcher, a status, and a way to refresh. Copying it into three useState hooks is how the player and the Monday board diverge.
The decision rule: if a reload must show the same completion, it is server state. If only this mount cares, it is local. If many components care and a reload may reset it, it is shared client state.
Why effects that fetch get you into trouble
useEffect can synchronize React with an external system. A fetch is such a system, and it is easy to get wrong:
The effect closes over lessonId. If you omit it from the dependency array, you show the previous lesson's data for the new id.
If you include it but ignore responses that belong to the previous id, a slow request overwrites the new screen.
Strict Mode in development runs the effect, cleans it up, and runs it again. A fetch without abort looks like a double request in development. That is a signal to cancel, not a reason to remove Strict Mode.
Setting state from props inside an effect to "sync" a query result creates a second cache.
You may still fetch in an effect for a small component if you handle cancellation and status explicitly. Once you have more than one screen, a cache library earns its place. This lesson shows both, so the library is not magic.
Query keys and caches
A cache is a map. TanStack Query v5 keys that map with queryKey, an array such as ['lesson', lessonId]. The id must be in the key. If you use ['lesson'] for every route, every lesson shares one entry and the late-response bug returns as a cache bug.
queryFn receives an AbortSignal as signal in the query function context. Pass it to fetch. When the query key changes or the component unmounts, the library aborts the in-flight request.
staleTime is how long the data is considered fresh. gcTime (v5) is how long unused data stays in memory. They are not authorization. A long staleTime on a shared device does not make private data public by itself, because the cache lives in that browser, but a wrong key or a cache hydrated from another user does. On the server, a QueryClient must be created per request. A global client on the server leaks one learner's data into another learner's render. Lesson 7 repeats this because it is the usual Next.js failure.
Mutations
A mutation is a write: mark complete, save a note. useMutation runs the function and reports isPending, isError, and isSuccess. On success, invalidate ['lesson', lessonId] so the next read refetches, or update the cached value if you understand the shape. Do not also setItems in a parallel useState unless that state is clearly a draft. Two caches drift.
Optimistic updates show the checkmark before the server agrees. They require a rollback on error. Skip them until the plain invalidate path is tested. A false checkmark during an outage is worse than a short wait.
Reducers for interaction state
Server status and interaction state are different. Fetch status belongs to the query. A multi-step "save note" widget can use a reducer:
Illegal combinations (saving and editing both true) are harder to represent if you use two booleans. The reducer returns the next state for a typed action. It stays pure and unit-tests without a DOM.
Context without a performance trap
Context updates re-render consumers. A context value of { items, playbackSeconds } that changes every tick re-renders the outline every tick. Split contexts: one for the lesson record, one for high-frequency UI if you truly need it. Often the high-frequency value should stay in the component that displays it.
Context is also a dependency-injection slot. QueryClientProvider is context. You wrap the tree once in main.tsx. Tests wrap with a new QueryClient so caches do not leak between tests (defaultOptions.queries.retry: false keeps failures fast).
Race conditions
If you do not use a library, this is the minimum contract:
Create an AbortController in the effect.
Pass controller.signal to fetch.
Cleanup calls controller.abort().
Ignore AbortError.
Include lessonId in the dependency array.
If you use TanStack Query, the key change plus signal is the same contract. Still ignore aborted errors in custom queryFn code if you throw them as user-facing failures.
AI and streaming, only as a boundary
A token stream is not server state until it is stored. Keep partial output in local state keyed by requestId, append text, and render it as text. Do not write the partial string into the lesson cache on each token. Do not post it as progress. A later lesson covers streaming UX. This lesson's rule prevents the cache from filling with half-finished model text that the next navigation displays as if it were the lesson body.
Architecture and Design Diagrams
flowchart TB
subgraph browser [Browser]
Provider[QueryClientProvider per session]
Player[LessonPlayer]
Query[useQuery key lesson plus id]
Mutation[useMutation mark complete]
View[LessonOutline props only]
end
subgraph server [Your API]
Route["GET and POST /api/lessons/:id"]
Auth[Session check on the server]
Store[(Progress store)]
end
Provider --> Player
Player --> Query
Player --> Mutation
Query --> View
Query --> Route
Mutation --> Route
Route --> Auth
Auth --> Store
text
navigation changes lessonId
|
v
queryKey ['lesson', lessonId] changes
|
+--> abort in-flight request for the previous id
|
v
fetch GET /api/lessons/:id with signal
|
+--> 200 JSON -> cache -> outline props
+--> 4xx/5xx -> error UI, outline unchanged or cleared
|
user toggles complete
|
v
POST /api/lessons/:id/complete
|
+--> 200 -> invalidate ['lesson', lessonId]
+--> 403 -> error UI, no local "success" cache write
Trust boundary: the query cache is a performance tool in one browser. The route handler is the security tool. A query key is not an access-control list.
Technical Explanation
On mount with lessonId = "react-components":
useQuery looks up ['lesson', 'react-components'].
If nothing fresh is cached, it calls queryFn with a signal.
fetchLesson checks response.ok, parses JSON, and runs a type guard. A 500 does not become an outline of undefined titles.
Status moves from pending to success. The view receives items.
If the learner navigates, the key changes, the signal aborts, and a new request starts. The aborted promise must not call a user-visible error state.
On mark complete:
useMutation sends a POST with the lesson id.
The server checks the session. This lesson's client cannot do that check for real.
On HTTP success, onSuccess invalidates the lesson query.
The query refetches. The checkbox matches the server.
On failure, isError is true and the cached outline is not edited.
useTransition is for keeping the current outline responsive while a non-urgent filter updates local state. It is not a retry mechanism and it does not cancel fetch. Do not wrap the mutation in startTransition and assume the network became cancellable.
Practical Implementation
Relative URLs only. No API keys in the client. The JSON shape is the one this course uses in the player; your route must return it or the type guard fails closed.
The status error's message includes a status code, not the response body. Response bodies can echo input. The UI in the enterprise example shows a fixed string per status class instead of error.message from the network.
LessonOutline is unchanged from lesson 5. That is the point of the split.
Empty state: if lesson.data.items.length === 0, render a specific empty message. Do not treat empty as an error. Pending, error, empty, and success are four outcomes.
Security
The browser will send whatever the mutation builds. The server must ignore client-supplied learner ids and use the session. This client posts itemId and a lesson id in the URL. It does not post a user id, a role, or a "force complete" flag. If a field is not the server's to trust, do not send it.
Cookies: prefer an HttpOnly session cookie set by your server over a token in localStorage. localStorage is readable by any script on the origin. This lesson's fetch calls are same-origin and omit a bearer token on purpose. Cross-origin APIs need an explicit credential and CORS design; do not add credentials: "include" to a third-party host as a experiment.
Query keys: include the lesson id. If the product is multi-tenant in one browser profile, include the tenant id too, and still enforce tenancy on the server. A key is not a permission.
Do not put the response body in logs or in the error paragraph. Status-class messages ("could not be loaded", "you do not have access") are enough. A 401 and a 404 can be distinguished in the UI without echoing the payload.
Model text stays out of dangerouslySetInnerHTML. Do not store prompts, keys, or hidden instructions in client state that gets serialized into an error report.
QueryClient on the server, when you reach lesson 7, is created inside the request. A module-level new QueryClient() in a server file is a cross-user leak.
Testing
tsx
// src/features/lesson-player/noteEditor.test.ts
import{ describe, expect, it }from"vitest";
import{ noteReducer }from"./noteEditor";
describe("noteReducer",()=>{
it("does not accept edits while saving",()=>{
const next =noteReducer({ status:"saving", draft:"hello"},{ type:"edit", draft:"changed"});
expect(await screen.findByText("The lesson could not be loaded.")).toBeTruthy();
});
});
Add a reducer test for submit-from-idle and fail-keeps-draft. For abort, call the effect hook with a changed lessonId under fake timers or assert that the request was created with a signal you abort; do not require a live server. Failure and success are both required. A suite that only mocks 200 is how the late error UI ships blank.
Performance
Set staleTime for data that can be a few seconds old so focus refetches do not stampede. The default in v5 is staleTime: 0, which refetches on mount and window focus. That is correct for a volatile price and noisy for a lesson outline.
Do not refetch in a loop by putting a new object in queryKey (['lesson', { lessonId }] inline is fine if the contents are stable; a new Date() in the key is not).
Keep LessonOutline free of queries so a list does not subscribe to the whole cache.
Split context so playback ticks do not re-render the outline.
useTransition can mark a filter update as non-urgent so typing stays responsive. It does not replace pagination.
Invalidate the specific key, not the entire client, after one checkbox.
Debounce note saves yourself if you add them. Do not persist on every keystroke to the progress API.
Cache memory (gcTime) is a client concern. It is not a CDN. Lesson 7 owns HTTP caching.
Enterprise Real-World Scenarios
Scenario A: Late response, wrong lesson
Navigation changed the id. The first request resolved last and called setLesson.
What good looks like. Abort on cleanup or change the query key and pass signal. Test by resolving the first fetch after the second id is rendered.
Scenario B: Context as a second database
The team wrote query data into context on every success and also read context in the outline. Invalidation updated the query and not the context.
What good looks like. The outline reads props from the component that called useQuery. Context holds the client or the theme, not a copy of the payload.
Scenario C: Optimistic complete during a 403
The checkbox flipped, the POST returned 403, and the rollback was forgotten. The learner believed they were done.
What good looks like. No optimistic update until rollback is tested. Invalidate only after response.ok. Show "you do not have access" without clearing unrelated UI.
Scenario D: Shared server QueryClient
A future server render used one module-scope client. Learner B's outline included learner A's completion.
What good looks like. Create the client per request on the server and per session in the browser. Include ids in keys anyway.
Scenario E: Error toast with the response body
A 400 body contained a fragment of the note. The toast library logged it to an analytics vendor.
What good looks like. Fixed copy for the status class. Detailed diagnostics stay in server logs with redaction, which later observability lessons cover.
Best Practices
Name the state class before you choose a tool: local, shared client, or server.
Put server state in one cache, not in context plus useState plus a module variable.
Include resource identity in the query key.
Pass AbortSignal into fetch.
Fail closed on unexpected JSON with a type guard.
Show pending, empty, error, and success as distinct UI.
Invalidate the specific query after a successful write.
Postpone optimistic updates until rollback tests exist.
Keep presentational components free of useQuery.
Create a new QueryClient per test and per server request.
Turn off query retries in tests.
Use a reducer when booleans would allow illegal combinations.
Do not store high-frequency values in a context that wide trees consume.
Prefer HttpOnly session cookies to tokens in localStorage.
Do not send user ids or roles the server should already know.
Do not render error.message from an API body to the learner.
Keep model streams out of the lesson query cache.
Same-origin fetch by default. Treat cross-origin credentials as a design change.
Verify TanStack Query v4 versus v5 names against the installed version.
Leave the lesson 5 component props intact so the App Router can render the same outline.
Common Mistakes and Anti-Patterns
Missing effect dependency. Symptom: stale lesson after navigation. Cause: empty dependency array. Fix: depend on lessonId and cancel.
No abort. Symptom: old data flashes after a fast click. Cause: the first promise still sets state. Fix: AbortController or query keys plus signal.
Boolean status pairs. Symptom: spinner and error together. Cause: loading and error updated separately. Fix: a status union or the query's status.
Shadow copy of server data. Symptom: refetch does not move the checkbox. Cause: useState(data) synced once. Fix: render lesson.data or invalidate.
Query key without id. Symptom: every lesson shows the first payload. Cause: ['lesson']. Fix: ['lesson', lessonId].
Module-level QueryClient on the server. Symptom: cross-user data. Cause: one cache for all requests. Fix: per-request client. Browser singletons are a different case.
Optimistic update without rollback. Symptom: success UI after 403. Cause: setState before the POST resolves. Fix: wait for success or roll back in onError.
Logging response bodies. Symptom: notes in a third-party logger. Cause: console.error(await response.text()) in the client. Fix: status code on the server, fixed string in the UI.
Global store for one screen's menu. Symptom: reset bugs and ceremony. Cause: Redux for isOpen. Fix: local state until a second distant writer exists.
Retry storm. Symptom: a 403 is requested three times and the UI waits. Cause: default retry on a permanent failure. Fix: retry network failures with a limit; do not retry 400 or 403 blindly. Configure retry deliberately.
Knowledge Check
1. What problem does the state split solve?
It stops server-owned completion from being stored as if the component owned it, and it stops a slow response from painting the previous lesson. Local interaction, shared UI, and server records fail differently and should not share one bag of useState.
2. What alternatives exist, and when would you choose each?
An effect plus AbortController is enough for one fetch with no cache. TanStack Query v5 is the right step when several screens share reads, deduping, and invalidation. Context fits rare shared values and dependency injection. Zustand or Redux Toolkit fits frequent client-only updates across a wide tree. None of them replace a server check. Choose useReducer when transitions are the complexity, not the transport.
3. Which identity and trust boundaries matter?
The query key identifies the cache entry and must include the lesson id. The session identifies the learner, and only the server sees it. The cache is per browser session on the client and must be per request on the server. Payloads are untrusted input and pass a type guard. Roles are not props the client may set.
4. What can fail, and how should the system respond?
Abort is not a user error. HTTP failures and invalid JSON are errors with fixed copy. 401 and 403 stay failures and do not update the cache. Empty lists are empty states. A mutation failure leaves the last successful query data in place. A stuck saving reducer state ends in fail so the draft remains editable.
5. How would you test quality, security, and failure?
Unit-test the reducer for illegal edits. Render LessonData with fetch mocked to 200 and to 500. Use a fresh QueryClient with retry: false. Assert the checkbox name and the fixed error string. Assert the client does not send a user id. Assert a changed lessonId does not display the previous payload. No production credentials in the test.
Interview Questions and Answers
Q1. How do you decide between useState, context, and a server cache?
If one component owns it and a reload can forget it, useState or useReducer. If many components share client-only data that changes rarely, context. If the server owns it, a query cache keyed by resource id. The mistake is using all three for the same payload.
Q2. Why does a fetch in useEffect race?
The effect starts a promise and does not automatically cancel it when lessonId changes. The older promise can resolve last and overwrite state. Cleanup must abort, and the code must ignore AbortError.
Q3. What is a query key?
The cache identity for a query. TanStack Query uses it to store and invalidate results. If two different resources share a key, they share data. Put the ids that change the response into the key.
Q4. What is the difference between staleTime and gcTime in TanStack Query v5?
staleTime controls when cached data is old enough to refetch. gcTime controls how long inactive data remains in memory. Neither is an access-control setting. v4 called the garbage-collection window cacheTime.
Q5. When would you not use a global store?
When the state is server-owned, or when only one component reads it. A store adds indirection and a second cache. Menu open flags and one-screen drafts do not need Redux.
Q6. How do you prevent cross-user cache leaks in server rendering?
Do not keep a module-level QueryClient in server code. Create one per request. Also key queries by resource id and authorize every request on the server so a wrong key is not your only defense.
Q7. What belongs in onSuccess of a mutation?
A cache update that matches the server's decision: typically invalidateQueries for that lesson's key. Not a second copy in context. Not an optimistic write you cannot roll back.
Q8. Why prefer an HttpOnly cookie to localStorage for a session?
Script on the page can read localStorage. An HttpOnly cookie is sent by the browser and is not readable by JavaScript. The server still needs CSRF defenses for cookie-authenticated writes; lesson 7 names origin checks for server actions. This lesson simply refuses to park tokens in localStorage.
Q9. How should the UI treat a 403?
As a failed command. Leave the cached server state unchanged, show a fixed message, and do not retry as if the call were a dropped packet. Hiding the control is optional UX. The server must keep refusing the write.
Q10. What does enabled do on useQuery?
It stops the query from running until a condition is true. enabled: lessonId.length > 0 avoids a request for an empty id. It is not a security feature.
Q11. Why validate JSON with a type guard?
response.json() is unknown in a strict codebase, and the network can return an error document, HTML from a proxy, or a partial object. Rendering data.items.map without a check throws or shows nonsense. Fail closed.
Q12. Where does streaming model output sit?
In local state for that request, rendered as text, discarded or explicitly saved by a later designed write. It is not merged into the lesson query on each token, and it is not completion.
Assignment
Problem. Connect the lesson 5 outline to server state with a cancelled read, a typed failure path, and a mutation that invalidates instead of shadowing state.
Tasks.
Implement fetchLesson with AbortSignal, response.ok, and a type guard. Use the relative /api/lessons/:id path only.
Implement either useLesson with cleanup abort or useLessonQuery on TanStack Query v5. If you use the library, pin the major version and use queryKey: ['lesson', lessonId].
Render pending, error, empty, and success. Error copy must not include the response body.
Add noteReducer and unit tests for edit-during-save and fail-keeps-draft.
POST completion without a client-supplied user id, and invalidate the lesson query only on success. Mock a 403 and show that the checkbox does not stick.
Mock fetch in tests for 200 and 500. Use a per-test QueryClient if you use the library.
Write a short note on where a QueryClient would be constructed in a future server render, and why a module singleton is rejected.
Deliverable. Source, test output, the state-classification table for every field you stored, and the server-client note. No secrets, no live tokens.
Challenge. Two tenants could theoretically be previewed in one staff browser. Extend the query key with a tenantId the server also checks, and describe what still fails if the key is correct but the route trusts a tenant id from the query string. The fix is server-side session-to-tenant binding, not a longer key.
Rubric. Architecture and state classification 20%. Implementation and types 25%. Security and privacy of errors, keys, and writes 20%. Tests for success, HTTP failure, and reducer edges 20%. Decision write-up 15%.
Lesson Summary
Server state is a cache of someone else's record, local state is interaction, and shared client state is the small remainder. Keys, cancellation, type guards, and invalidation are what keep TechLearningPro's outline aligned with the API after a fast navigation. Context and global stores do not get a second copy of that payload. The view components from lesson 5 still take props.
Next.js App Router and Full-Stack React moves the first read toward the server and makes the client boundary explicit. The React course remains the hook reference, and the Next.js course is where App Router caching gets a full track of its own. Take the query key rule with you: identity in the key, authority on the server.