César Felipe

11 min readUpdated

Frontend Architecture That Survives Time

Frontend codebases decay through unmanaged coupling. Vertical slices with validated services, typed errors and enforced boundaries keep them changeable.

  • Architecture
  • React
  • Frontend
On this page

Reducing Coupling, Increasing Cohesion

Frontend architecture deserves the same level of care as backend architecture.

Not because frontend is inherently more complex, but because frontend applications are long-lived systems under constant change. They evolve with the product, absorb business rules, integrate with multiple backends, and accumulate state, caching, and edge cases over time.

The problem is that frontend systems look simple early on.

You can ship fast with a few components, some hooks, and direct API calls. For a while, everything feels productive.

Then, months later, patterns start to break down:

  • Small changes ripple through unrelated areas
  • UI components depend on API response details
  • Shared hooks accumulate special cases
  • Cache behavior becomes implicit knowledge
  • Refactoring feels risky, even when the change is conceptually small

This isn’t caused by React, or libraries, or “bad developers”.

It’s caused by uncontrolled relationships inside the codebase.

At its core, it’s a failure to manage coupling and cohesion.

Coupling and cohesion are the real architectural axis

Coupling and cohesion are not academic concepts. They are practical forces that decide whether a codebase remains flexible or slowly locks itself in place.

Coupling

Coupling is about how much a piece of code depends on knowledge of other pieces.

High coupling in frontend systems often shows up as:

  • UI components knowing backend response shapes
  • Hooks calling other hooks across features
  • “Shared” utilities encoding business rules
  • Cache keys and invalidation logic scattered everywhere
  • Error handling based on strings instead of types

The result is that change becomes risky. You can no longer reason locally. Every modification feels like it might break something you didn’t touch.

Cohesion

Cohesion is the opposite force. It measures how closely related the responsibilities inside a unit are. High cohesion means that things that change together live together.

High cohesion looks like:

  • Domain rules are defined in one place
  • Data fetching, validation, and state updates align around a single feature
  • Most changes stay inside one bounded area.

Good frontend architecture is not about eliminating complexity. It’s about containing it.

Before: four UI components and four API services tangled through shared hooks and global utils. After: three feature modules, each with its own containers, hooks, services and domain, reaching the backend only through an API gateway

The core approach: a modular monolith of vertical slices

The approach I keep coming back to is a modular monolith frontend, structured as vertical slices.

There is still a single application, a single runtime, a single router, and a single deploy. What changes is the internal structure. Instead of organizing code by technical layers globally, the app is split into modules that each own a feature end-to-end.

Each module contains its own domain definitions, service integrations, hooks and containers. The goal is not to isolate everything, but to make ownership explicit and change predictable.

The tooling itself is fairly standard: Vite, Vitest, Tailwind, TanStack Query, TanStack Router, ESLint, Prettier, Zod, and Playwright. None of these tools are the point on their own. What matters is how responsibilities are divided and enforced.

Make the dependency graph visible in the folder structure

modules/
  billing/
    domain/
    services/
    hooks/
    containers/
    state/
    errors.ts
    index.ts
infrastructure/
routes/
ui/
e2e/

This is not about aesthetics or navigation convenience. It’s about making dependencies visible. When structure mirrors behavior, it becomes easier to see when something is in the wrong place.

There are a few rules that make this structure hold over time:

  • UI components never call services directly
  • Services never return unvalidated data
  • Server state lives in TanStack Query
  • Routes compose modules, but modules remain unaware of routing.
  • Cross-module access goes through explicit public APIs.

These constraints exist to keep coupling explicit and cohesion high.

From global technical layers to a vertical sliceBefore: billing files are scattered across global technical-layer folders (components, hooks, services, types and utils), mixed with other features' files and tangled dependencies. After: they move into one module, modules/billing, with an index.ts public API on top, then containers, hooks (next to state), services, and domain with errors.ts. Dependency arrows point one way: routes to the module's index.ts, index.ts to containers, containers to hooks and to the shared ui folder, hooks to services, services to domain, errors.ts and the shared infrastructure logger. Another module may reach billing only through its public API; a dashed deep import from that module into billing's services is crossed out as blocked by lint rules.MODULES/BILLING/ANOTHER MODULEHeader.tsxProfilePage.tsxuseUser.tsuseFormatDate.tsapi.tsuserService.tsuser.tsformat.tsSubscriptionContainer.tsxcontainers/useChangePlan.tshooks/fetchSubscription.tsservices/subscription.tsdomain/errors.tsmodule rootroutes/compose modulesindex.tspublic APIstate/ui/dumb UI componentsinfrastructure/loggercontainers/components/hooks/services/types/ · utils/BEFORE · ORGANISED BY TECHNICAL LAYERAFTER · VERTICAL SLICEarrows point the alloweddependency directionpublic APIDeep import into anothermodule: blocked by lint rulesFrom global technical layers to a vertical sliceBefore: billing files are scattered across global technical-layer folders (components, hooks, services, types and utils), mixed with other features' files and tangled dependencies. After: they move into one module, modules/billing, with an index.ts public API on top, then containers, hooks (next to state), services, and domain with errors.ts. Dependency arrows point one way: routes to the module's index.ts, index.ts to containers, containers to hooks and to the shared ui folder, hooks to services, services to domain, errors.ts and the shared infrastructure logger. Another module may reach billing only through its public API; a dashed deep import from that module into billing's services is crossed out as blocked by lint rules.MODULES/BILLING/ANOTHER MODULEHeader.tsxuseUser.tsuseDate.tsapi.tsuser.tsformat.tsSubscriptionContainer.tsxcontainers/useChangePlan.tshooks/fetchSubscription.tsservices/subscription.tsdomain/errors.tsmodule rootroutes/compose modulesindex.tspublic APIstate/ui/dumb UIinfrastructure/loggercontainers/components/hooks/services/types/ · utils/BEFORE · BY TECHNICAL LAYERAFTER · VERTICAL SLICEDeep import into another module(dashed): blocked by lint rulesArrows point the allowed dependency direction

From global technical layers to a vertical slice

  • Before: the billing feature is scattered across global folders: SubscriptionContainer.tsx in components/, useChangePlan.ts in hooks/, fetchSubscription.ts in services/, subscription.ts and errors.ts in types/ and utils/. Other features’ files sit next to them, and dependencies cross every layer.
  • After: the same files move into one module, modules/billing/, with index.ts as its public API, then containers/, hooks/ (next to state/), services/, domain/ and errors.ts.
  • Dependencies point one way: routes/ → index.ts → containers → hooks → services → domain and errors. Containers render shared ui/ components, and services use the shared infrastructure/ logger.
  • Another module reaches billing only through index.ts. A deep import into billing/services is blocked by lint rules.

What lives inside a module

Each module represents a vertical slice of the application. It owns one domain concept and everything needed to support it.

Inside modules/billing: containers call hooks, hooks call services, services validate data against the domain’s Zod schemas, and named domain errors thrown by services flow back up through hooks to the containers

Domain: the source of truth

The domain layer defines what the system considers valid. This is where Zod schemas live, along with inferred types and pure helpers. There is no IO here, no React, no logging. Just rules and contracts.

import { z } from "zod";

export const planSchema = z.enum(["free", "pro", "enterprise"]);
export type Plan = z.infer<typeof planSchema>;

export const subscriptionSchema = z.object({
 id: z.string().min(1),
 plan: planSchema,
 status: z.enum(["active", "past_due", "canceled"]),
 renewsAt: z.iso.datetime(),
});
export type Subscription = z.infer<typeof subscriptionSchema>;
ts

(This is Zod 4. On Zod 3, z.string().datetime() does the same job; Zod 4 still accepts it but marks it deprecated.)

Errors: A Single Failure Vocabulary

Failure modes are part of the domain, not an afterthought. When errors are not modeled explicitly, they leak out as string comparisons and ad-hoc conditionals scattered across the UI.

Keeping errors centralized gives the system a shared language for failure.

export class FetchUserSubscriptionError extends Error {
  readonly code = "FETCH_USER_SUBSCRIPTION_ERROR";

  constructor(options?: ErrorOptions) {
    super("Failed to communicate with subscription service", options);
    this.name = "FetchUserSubscriptionError";
  }
}

export class FetchUserSubscriptionInvalidResponseError extends Error {
  readonly code = "FETCH_USER_SUBSCRIPTION_INVALID_RESPONSE";

  constructor(options?: ErrorOptions) {
    super("Subscription service returned an invalid response", options);
    this.name = "FetchUserSubscriptionInvalidResponseError";
  }
}
ts

A few details here are load-bearing:

  • In a subclass, this doesn’t exist until super() returns. Assigning this.code before it throws a ReferenceError at runtime. A class field avoids the problem, because field initializers run right after super().
  • readonly with a string literal gives each class a literal code type you can switch on.
  • Setting name keeps stack traces and error trackers readable, instead of a wall of Error.
  • ErrorOptions lets the service attach the original failure as cause. You translate the error without losing the real reason.

This makes error handling predictable, logging structured, and UI mapping consistent.

Services: where IO and observability belong

Services form the boundary between the frontend and the outside world. That makes them the natural place for IO, validation, and observability.

A service performs the request, validates the response using domain schemas, throws domain-specific errors, and emits structured logs.

import { z } from "zod";
import { subscriptionSchema, type Subscription } from "../domain/subscription";
import {
  FetchUserSubscriptionError,
  FetchUserSubscriptionInvalidResponseError,
} from "../errors";
import { logger } from "@/infrastructure/logger";

export async function fetchSubscription(): Promise<Subscription> {
  logger.info("billing.fetch_subscription.started");

  let response: Response;
  try {
    response = await fetch("/api/subscription");
  } catch (cause) {
    logger.error("billing.fetch_subscription.network_error");
    throw new FetchUserSubscriptionError({ cause });
  }

  if (!response.ok) {
    logger.error("billing.fetch_subscription.http_error", {
      status: response.status,
    });
    throw new FetchUserSubscriptionError();
  }

  const json: unknown = await response.json().catch(() => undefined);
  const parsed = subscriptionSchema.safeParse(json);

  if (!parsed.success) {
    logger.error("billing.fetch_subscription.invalid_response", {
      issues: z.flattenError(parsed.error),
    });
    throw new FetchUserSubscriptionInvalidResponseError({ cause: parsed.error });
  }

  logger.info("billing.fetch_subscription.success");
  return parsed.data;
}
ts

Two failure paths are easy to forget. fetch only rejects when the request never completes (offline, DNS, CORS), and a 500 is a perfectly successful fetch with ok: false, so both need handling. And a body that isn’t JSON at all is just another invalid response, so it goes through the same schema check instead of escaping as a raw SyntaxError. Whatever happens, the caller only ever sees a domain error.

Putting observability here produces signal instead of noise. Logs are tied to domain actions, not UI events.

Eight numbered steps of a request: user interaction, container, hook triggers a TanStack Query query or mutation, service calls the API, service validates with Zod; valid data returns to the hook cache, invalid data throws a domain error that the container maps to UI state

Hooks: one place for server-state behavior

Hooks define how server state behaves in the application. Cache keys, stale times, invalidation rules, optimistic updates, and rollback logic all live here.

This centralization matters. When cache behavior is spread across components, bugs become invisible.

It starts with the query key. It’s defined once, next to the hooks that use it, and nothing outside the module ever types it by hand:

import { useQuery } from "@tanstack/react-query";
import { fetchSubscription } from "../services/fetch-subscription";

export const subscriptionQueryKey = ["billing", "subscription"] as const;

export function useSubscription() {
  return useQuery({
    queryKey: subscriptionQueryKey,
    queryFn: fetchSubscription,
    staleTime: 60_000,
  });
}
ts

A cache key copied into a second file is a cache bug waiting for its first refactor.

Optimistic updates are a good example. When done casually, they introduce subtle inconsistencies. When done deliberately, they improve perceived performance without sacrificing correctness.

import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Subscription } from "../domain/subscription";
import { changePlan } from "../services/change-plan"; // (nextPlan: Plan) => Promise<Subscription>
import { subscriptionQueryKey } from "./use-subscription";

export function useChangePlan() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: changePlan,
    onMutate: async (nextPlan) => {
      await queryClient.cancelQueries({ queryKey: subscriptionQueryKey });

      const previous =
        queryClient.getQueryData<Subscription>(subscriptionQueryKey);

      queryClient.setQueryData<Subscription>(subscriptionQueryKey, (current) =>
        current ? { ...current, plan: nextPlan } : current
      );

      return { previous };
    },
    onError: (_error, _nextPlan, context) => {
      if (context?.previous) {
        queryClient.setQueryData(subscriptionQueryKey, context.previous);
      }
    },
    onSettled: () =>
      queryClient.invalidateQueries({ queryKey: subscriptionQueryKey }),
  });
}
ts

Each step is there for a reason. cancelQueries stops an in-flight refetch from landing after the optimistic write and overwriting it with stale data. The snapshot taken in onMutate is what makes the rollback possible. And onSettled returns the invalidation promise on purpose: the mutation stays pending until the refetch finishes, so the UI never flashes the old plan between “saved” and “refreshed”.

Optimistic plan change: the user changes plan, onMutate updates the cache, the UI updates immediately, and the request runs in the background; on success the cache is confirmed, on error onError restores the previous snapshot

Containers: where logic meets UI

Containers glue hooks to dumb UI components. They coordinate data, loading states, error mapping, and composition. UI components remain focused on rendering and interaction, without knowing where data comes from or how it fails.

import { ErrorState, Spinner } from "@/ui";
import { FetchUserSubscriptionInvalidResponseError } from "../errors";
import { useSubscription } from "../hooks/use-subscription";
import { SubscriptionPanel } from "./subscription-panel";

function subscriptionErrorMessage(error: Error) {
  if (error instanceof FetchUserSubscriptionInvalidResponseError) {
    return "Something is wrong with your subscription data. Contact support.";
  }
  return "We couldn’t load your subscription. Try again in a moment.";
}

export function SubscriptionContainer() {
  const subscription = useSubscription();

  if (subscription.isPending) return <Spinner />;

  if (subscription.isError) {
    return <ErrorState message={subscriptionErrorMessage(subscription.error)} />;
  }

  return <SubscriptionPanel subscription={subscription.data} />;
}
tsx

Two things worth noticing. The container maps domain errors to copy written for users; it never renders error.message, which was written for engineers and logs. And it checks isPending, not isLoading: in TanStack Query v5, isPending is what tells TypeScript that data is defined after the error check. isLoading is only true while the first fetch is actually running, so it doesn’t narrow data.

UI components remain unaware of fetching, caching, or failure modes. This separation keeps presentation simple and changeable.

Enforce the architecture, or it won’t last

None of this works without enforcement.

Lint rules, path aliases, and explicit module public APIs are what keep boundaries intact as teams grow and code changes hands. Architecture survives not because people remember the rules, but because the system makes breaking them difficult.

The public API is a plain index.ts that exports only what other parts of the app are allowed to use:

export { SubscriptionContainer } from "./containers/subscription-container";
export { useSubscription } from "./hooks/use-subscription";
export type { Plan, Subscription } from "./domain/subscription";
ts

Services, schemas and query keys are not exported. If another module needs them, that’s a conversation about the boundary, not an import.

The enforcement can start with ESLint’s built-in no-restricted-imports, no plugin needed:

// eslint.config.js
export default [
  {
    files: ["src/**/*.{ts,tsx}"],
    rules: {
      "no-restricted-imports": ["error", {
        patterns: [{
          group: ["@/modules/*/*"],
          message: "Import other modules through their public API: @/modules/<name>",
        }],
      }],
    },
  },
  {
    files: ["src/ui/**/*.{ts,tsx}"],
    rules: {
      "no-restricted-imports": ["error", {
        patterns: [{
          group: ["@/modules/**"],
          message: "Shared UI must not depend on feature modules.",
        }],
      }],
    },
  },
];
js

The first rule blocks deep imports like @/modules/billing/services/fetch-subscription while allowing @/modules/billing. Inside a module, files use relative imports, so the rule doesn’t get in their way. The second keeps shared UI from quietly growing a dependency on a feature.

It has a gap: a relative path like ../../billing/services walks straight past an alias-based rule. When the codebase gets big enough for someone to try that, I move to a dedicated plugin such as eslint-plugin-boundaries, which understands element types (module, ui, infrastructure) instead of string patterns. Either way, the rule runs in CI. A boundary that only fails on someone’s machine is a suggestion.

Allowed and blocked imports: routes and other modules enter billing only through its index.ts public API, containers import ui, services import infrastructure; lint blocks ui importing billing services and another module deep-importing billing’s domain

Final thoughts

This architecture works because it aligns structure with reality.

Features change independently. Data is validated at boundaries. IO is observable. Errors are named. Coupling is constrained. Cohesion is structural.

Frontend systems don’t fail because people are careless.

They fail because relationships grow unchecked.

This is how I keep those relationships manageable over time, and it’s what has worked for me over the years.

Key takeaways

  • Frontend systems decay through uncontrolled relationships in the code: manage coupling and cohesion explicitly.
  • Structure the app as a modular monolith of vertical slices: one app, one router, one deploy, with each module owning a feature end to end.
  • Keep a few hard rules: UI never calls services directly, services never return unvalidated data, server state lives in TanStack Query, and cross-module access goes through public APIs.
  • Give each module a domain layer (Zod schemas, no IO), named error classes, services that validate and log, hooks that own cache behavior, and containers that glue data to dumb UI.
  • Services translate every failure (network, HTTP status, invalid body) into a domain error with the original as cause; containers map those errors to user-facing copy, never to error.message.
  • Define query keys once, inside the module, and keep optimistic updates deliberate: cancel, snapshot, roll back, invalidate.
  • Enforce boundaries with lint rules in CI, path aliases and module public APIs; architecture survives because breaking the rules is hard, not because people remember them.

I’d love to hear what patterns you’ve seen hold up long-term in real frontend codebases.