FullStack Engineering CourseLesson 18 of 20 22 min
React Architecture: State, Data Fetching, Next.js and Design Systems
How React renders
A React app is a tree of components: functions that take inputs (props) and return a description of the UI. When a component's state changes, React calls the component again (re-renders it), compares the new description with the previous one, and updates only the parts of the page that changed. This comparison is called reconciliation.
Three facts explain most React performance and correctness problems:
- When a component re-renders, all of its children re-render too, unless they are memoised (React.memo, or the React Compiler, which can memoise automatically).
- In lists, keys tell React which item is which. Use a stable ID (claim.id), never the array index, or React mixes up items when the list is reordered or filtered.
- Hooks (useState, useEffect and the rest) must be called in the same order on every render: never inside conditions or loops.
Most front-end architecture is about one question: where should each piece of state live?
Kinds of state
| Kind | Examples | Where it belongs |
|---|---|---|
| Local UI state | Is this panel open? What is typed in this box? | useState or useReducer in the component |
| Shared client state | Selected tenant, theme, a multi-step wizard's progress | Context for rarely changing values; Redux Toolkit or Zustand for larger, frequently changing state |
| Server state | Claims, payers, the current user's profile | TanStack Query or RTK Query: a cache of server data |
| URL state | Filters, sort order, current page, selected claim | The URL (search parameters), so it can be bookmarked and shared |
| Form state | Field values, validation errors, touched fields | A form library such as React Hook Form, with a schema (Zod) for validation |
The most common mistake is treating server state as client state: fetching data in useEffect and copying it into a global store. Then you must handle loading, errors, caching, refreshing and keeping copies in step by hand. Server state is really a cache of data owned by the server, so use a tool built for that.
Context and its limits
Context passes a value down the tree without passing props through every level. It suits values that rarely change, such as the signed-in user, the theme or the current tenant. Every component that reads a context re-renders whenever its value changes, so a context that holds frequently changing data (or a new object created on every render) can re-render large parts of the app. Split contexts by how often they change, memoise the value, or move fast-changing state to a store that lets components subscribe to only the part they need.
Redux Toolkit
Redux keeps shared client state in one store. Components dispatch actions, and reducers calculate the new state. Redux Toolkit (RTK) is the modern way to write Redux: createSlice removes most of the boilerplate, and Immer lets reducers be written as if they changed state directly while keeping it immutable underneath:
import { createSlice, configureStore, type PayloadAction } from "@reduxjs/toolkit";
type ClaimFilters = { status: "all" | "pending" | "approved" | "denied"; payerCode: string | null };
const filtersSlice = createSlice({
name: "claimFilters",
initialState: { status: "all", payerCode: null } as ClaimFilters,
reducers: {
statusChanged(state, action: PayloadAction<ClaimFilters["status"]>) {
state.status = action.payload; // looks like mutation; Immer makes it immutable
},
payerChanged(state, action: PayloadAction<string | null>) {
state.payerCode = action.payload;
},
},
});
export const { statusChanged, payerChanged } = filtersSlice.actions;
export const store = configureStore({ reducer: { claimFilters: filtersSlice.reducer } });Redux pays off for large apps with complex shared state, where its predictability and developer tools (time-travel debugging) help. For small amounts of shared state, Context or a lighter library such as Zustand is simpler. RTK Query, part of Redux Toolkit, handles server state for teams already using Redux.
Server state with TanStack Query
TanStack Query (formerly React Query) fetches, caches and refreshes server data. Each piece of data has a query key. Components that use the same key share one cache entry and one request. It handles loading and error states, retries, refreshing stale data in the background (stale-while-revalidate), and refetching when the user returns to the tab:
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
export function useClaim(id: number) {
return useQuery({
queryKey: ["claim", id],
queryFn: () => api.getClaim(id),
staleTime: 30_000, // treat it as fresh for 30 seconds
});
}
function ClaimHeader({ id }: { id: number }) {
const { data: claim, isPending, error } = useClaim(id);
if (isPending) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
return <h1>Claim {claim.id}: {claim.status}</h1>;
}Optimistic updates
An optimistic update shows the result of an action immediately, before the server confirms it, and undoes it if the server rejects it. The app feels instant, which suits actions that almost always succeed. With TanStack Query:
- Before the request: cancel any refetch in progress, save the current data, and update the cache with the expected result.
- If the request fails: put the saved data back, and tell the user.
- When the request finishes, either way: refetch, so the screen shows what the server really holds.
export function useApproveClaim() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => api.approveClaim(id),
onMutate: async (id) => {
await queryClient.cancelQueries({ queryKey: ["claim", id] });
const previous = queryClient.getQueryData<Claim>(["claim", id]);
queryClient.setQueryData<Claim>(["claim", id], (old) => old && { ...old, status: "Approved" });
return { previous }; // passed to onError as context
},
onError: (_error, id, context) => {
queryClient.setQueryData(["claim", id], context?.previous); // roll back
toast.error("The claim could not be approved. It may have changed; please reload.");
},
onSettled: (_data, _error, id) =>
queryClient.invalidateQueries({ queryKey: ["claim", id] }), // sync with the server
});
}Use optimistic updates for quick, low-risk actions (marking as read, reordering, toggling). For actions with real consequences or a high chance of failure, such as submitting a payment, show a clear pending state and wait for the server instead. If the server returns 412 or 409 (lesson 5), explain the conflict rather than silently rolling back.
Error boundaries
Without protection, an error thrown while rendering any component removes the whole React tree and leaves a blank page. An error boundary catches rendering errors in the components below it and shows a fallback instead. Place them around independent parts of the page, so one broken widget does not take down the rest:
import { ErrorBoundary, type FallbackProps } from "react-error-boundary";
function PanelError({ error, resetErrorBoundary }: FallbackProps) {
return (
<div role="alert">
<p>This panel could not be loaded.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
export function ClaimPage({ id }: { id: number }) {
return (
<>
<ErrorBoundary FallbackComponent={PanelError} onError={(e) => telemetry.trackException(e)}>
<ClaimDetails id={id} />
</ErrorBoundary>
<ErrorBoundary FallbackComponent={PanelError}>
<PaymentHistory id={id} /> {/* fails on its own, without hiding the claim details */}
</ErrorBoundary>
</>
);
}Error boundaries only catch errors during rendering. Errors in event handlers and async code (a failed fetch in a click handler) must be caught there, or surfaced through the query library's error state. Report caught errors to your monitoring (lesson 16).
Rendering strategies and Next.js
Where the HTML is produced affects speed, search engine visibility and cost:
| Strategy | HTML is produced | Good for | Trade-offs |
|---|---|---|---|
| CSR (client-side rendering) | In the browser, by JavaScript | Apps behind a login, such as dashboards and internal tools | Slower first load; content invisible to search engines until JavaScript runs |
| SSR (server-side rendering) | On the server, for every request | Pages with personalised or frequently changing data that must load fast | Server cost per request; slower if data fetching is slow |
| SSG (static site generation) | At build time, once | Marketing pages, documentation, blogs | Content is only as fresh as the last build |
| ISR (incremental static regeneration) | Statically, then regenerated in the background after a set time or on demand | Large catalogues and content that changes occasionally | Visitors may briefly see slightly old content |
Next.js supports all four. Its App Router adds React Server Components (RSC): components that run only on the server. They can read data directly (from an API or a database), and their code is never sent to the browser, so pages ship less JavaScript and secrets stay on the server. Components that need interactivity (state, effects, event handlers) are marked with "use client" and run in the browser as usual. Server Components can render Client Components and pass them data as props:
// app/claims/[id]/page.tsx: a Server Component (the default in the App Router)
export const revalidate = 60; // ISR: regenerate this page at most once a minute
export default async function ClaimPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const claim = await getClaim(Number(id)); // runs on the server; tokens never reach the browser
return (
<main>
<ClaimSummary claim={claim} /> {/* server-rendered, no JavaScript shipped */}
<ApproveButton claimId={claim.id} /> {/* a Client Component for interactivity */}
</main>
);
}
// app/claims/[id]/ApproveButton.tsx
"use client";
export function ApproveButton({ claimId }: { claimId: number }) {
const approve = useApproveClaim();
return <button onClick={() => approve.mutate(claimId)} disabled={approve.isPending}>Approve</button>;
}Suspense boundaries let the server stream a page in pieces: the shell appears at once, and slower parts (a payment history that calls a slow service) arrive when ready. Server Actions let a form call a server function directly, without writing an API route. For an internal app behind a login, a plain client-rendered SPA built with Vite is often simpler; choose Next.js when first-load speed, SEO or server-side data access matter.
Structuring a large SPA
- Organise code by feature (claims, payments, reports), each with its own components, hooks, API calls and tests, rather than by type (all components in one folder, all hooks in another).
- Generate the API client and its TypeScript types from the OpenAPI document (lesson 4), so the front end breaks at compile time when the contract changes.
- Use a router that supports nested layouts and data loading (React Router or TanStack Router), and keep filters and selections in the URL.
- Split code by route with lazy loading, so users download only the screens they open (lesson 19).
- Use TypeScript in strict mode, and avoid any. Types are the cheapest tests you will write.
- For browser apps that call protected APIs, prefer the BFF pattern (lessons 8 and 12): the browser holds a secure cookie, not access tokens.
Design systems and Storybook
A design system is a shared set of design tokens (named values for colours, spacing and type, such as color-primary or space-4), components (Button, TextField, DataTable, Dialog) and guidelines. It keeps a large app, or several apps and micro-frontends, consistent, and it means accessibility (lesson 19) is built in once, in the components, instead of being solved again on every screen.
Storybook is a workshop for building and documenting components in isolation. Each story renders a component in one state (default, loading, error, disabled, long text), which makes it easy to review every state, document usage for other teams, and run visual regression tests (screenshots compared on every change) and accessibility checks automatically:
// Button.stories.tsx
import type { Meta, StoryObj } from "@storybook/react";
import { Button } from "./Button";
const meta: Meta<typeof Button> = { component: Button, title: "Design system/Button" };
export default meta;
export const Primary: StoryObj<typeof Button> = { args: { variant: "primary", children: "Submit claim" } };
export const Loading: StoryObj<typeof Button> = { args: { variant: "primary", loading: true, children: "Submitting" } };
export const Disabled: StoryObj<typeof Button> = { args: { disabled: true, children: "Submit claim" } };Monorepos and build tools
A monorepo keeps several apps and shared packages (the design system, the API client, utilities) in one repository. Changes to a shared package and its users happen in one pull request, and there is one set of tooling. Nx and Turborepo make monorepos fast:
- They understand the dependency graph between projects, and build and test only the projects affected by a change.
- They cache build and test results, locally and remotely, so unchanged projects are not rebuilt by anyone.
- They enforce boundaries, such as stopping one feature from importing another feature's internals.
Vite is the common build tool for new React projects: very fast development server start-up and hot reloading, with Rollup for optimised production builds. Webpack remains widespread in older projects and is still the reference for Module Federation (micro-frontends, lesson 8), though Rspack and Vite plugins now support it too.
Testing React components
React Testing Library tests components the way users use them: find elements by role, label or text, interact with them, and check what the user would see. Tests written this way survive refactoring and encourage accessible markup:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
test("shows a validation message when the amount is missing", async () => {
const onSubmit = vi.fn(); // Vitest; jest.fn() in Jest
render(<NewClaimForm onSubmit={onSubmit} />);
await userEvent.type(screen.getByLabelText(/procedure code/i), "99213");
await userEvent.click(screen.getByRole("button", { name: /submit claim/i }));
expect(await screen.findByText(/amount is required/i)).toBeInTheDocument();
expect(onSubmit).not.toHaveBeenCalled();
});Mock the network, not the components: tools such as Mock Service Worker (MSW) intercept fetch calls in tests and in development, so components run their real data-fetching code.
Check your understanding
| Question | Short answer |
|---|---|
| Why use a stable key in lists? | So React matches items correctly when the list changes; array indexes cause mixed-up state. |
| Where should server data live? | In a server-state cache such as TanStack Query or RTK Query, not copied into a global store by hand. |
| When is Context a poor fit? | For frequently changing values: every consumer re-renders on each change. |
| When is Redux Toolkit worth it? | For large apps with complex shared client state that benefit from its predictability and tooling. |
| What are the steps of an optimistic update? | Save and update the cache before the request, roll back on error, and refetch when it settles. |
| What do error boundaries not catch? | Errors in event handlers and async code. |
| CSR, SSR, SSG or ISR? | CSR for apps behind a login; SSR for fast personalised pages; SSG for static content; ISR for content that changes occasionally. |
| What is a React Server Component? | A component that runs only on the server, can fetch data directly, and ships no JavaScript to the browser. |
| What does a design system provide? | Shared tokens, components and guidelines, with accessibility and consistency built in. |
| What do Nx and Turborepo add to a monorepo? | Affected-only builds and tests, caching of results, and enforced boundaries between projects. |
Summary
- Decide where each kind of state lives: local, shared, server, URL or form.
- Use TanStack Query (or RTK Query) for server state, Context for rarely changing shared values, and Redux Toolkit or Zustand for complex client state.
- Use optimistic updates for quick, low-risk actions, with rollback and refetch.
- Wrap independent parts of the page in error boundaries and report errors to monitoring.
- Pick a rendering strategy per page; in Next.js, render on the server by default and add Client Components for interactivity.
- Organise by feature, generate the API client from OpenAPI, and keep tokens out of the browser with a BFF.
- Build a design system documented in Storybook, use a monorepo tool for shared packages, and test components the way users use them.
The next lesson covers web performance and front-end security: Core Web Vitals, code splitting, virtualisation, memoisation, debouncing, images, web workers and PWAs, accessibility and internationalisation, and protection against XSS and CSRF with CSP and secure token handling.
Comments