Skip to content
Rittick DattaFULL STACK DEVELOPER

2026-10-01 · 8 min read

Structuring Large React Applications

Architectural decisions for maintaining growing React codebases.

Structuring Large React Apps — React Architecture Guide

Structuring Large React Apps

A React application rarely becomes difficult to maintain because it has too many components. The trouble usually starts when responsibilities blur: features reach into each other's internals, server data is copied into global stores, and changing one workflow requires editing files across the entire repository.

A scalable structure is not the one with the most folders. It is the one that makes ownership, dependencies, and change boundaries obvious.

1. Start with boundaries, not folders

Before choosing a directory layout, identify:

  • Features: What distinct user workflows does the product support?
  • Shared capabilities: What is genuinely reused across features?
  • Data ownership: Which module owns fetching, updating, and validating each resource?
  • Dependency direction: Which parts of the app are allowed to import which others?

For a dashboard, features might include authentication, billing, analytics, and settings. Each should be understandable without reading the entire application.

2. Prefer feature-oriented organization

A small app can start with components/, hooks/, and utils/. As it grows, these folders often become dumping grounds with no clear owners.

A feature-oriented layout groups code that changes together:

src/
├── app/
│   ├── providers/
│   ├── router/
│   └── App.tsx
├── features/
│   ├── auth/
│   │   ├── api/
│   │   ├── components/
│   │   ├── hooks/
│   │   ├── model/
│   │   └── index.ts
│   ├── billing/
│   │   ├── api/
│   │   ├── components/
│   │   ├── hooks/
│   │   ├── model/
│   │   └── index.ts
│   └── analytics/
│       ├── api/
│       ├── components/
│       └── index.ts
├── shared/
│   ├── ui/
│   ├── lib/
│   ├── api/
│   └── types/
└── main.tsx

The folders inside a feature are optional. Add them when the code needs them, not as empty scaffolding.

Keep a feature's public API small

Other features should import from a feature's entry point rather than its internal file paths:

// features/billing/index.ts
export { BillingSummary } from './components/BillingSummary';
export { useInvoices } from './hooks/useInvoices';
export type { Invoice } from './model/types';
// Prefer
import { BillingSummary } from '@/features/billing';

// Avoid reaching into implementation details
// import { BillingSummary } from "@/features/billing/components/BillingSummary";

This allows the billing team to reorganize internal files without breaking unrelated code.

3. Establish dependency rules

A useful default dependency direction is:

app → features → shared
  • app/ composes routes, providers, and top-level configuration.
  • features/ owns business workflows and domain-specific UI.
  • shared/ contains generic building blocks without feature-specific knowledge.

Avoid circular imports and direct cross-feature access to internal modules. If two features share a concept, consider whether it belongs in a stable shared domain module or should be exposed through one feature's public API.

Important: Do not move something into shared/ simply because two files use it. Premature sharing can create coupling. A little duplication is sometimes cheaper than a poorly designed abstraction.

4. Separate server state from UI state

Not all state belongs in the same place.

State categoryExamplesTypical home
Local UI stateDialog visibility, form draftComponent state
URL stateSearch term, page, selected filtersRouter/search parameters
Server stateUser profile, invoices, analytics dataQuery/cache library
Shared client stateSidebar preferences, multi-step flowContext or a small store
Form stateInputs, validation errorsForm library or local hooks

The distinction matters because server state has its own lifecycle: fetching, caching, invalidation, retries, and synchronization.

For example, with TanStack Query:

import { useQuery } from '@tanstack/react-query';

async function fetchInvoices() {
  const response = await fetch('/api/invoices');
  if (!response.ok) throw new Error('Unable to load invoices');
  return response.json();
}

export function useInvoices() {
  return useQuery({
    queryKey: ['invoices'],
    queryFn: fetchInvoices,
  });
}

This is an example, not a requirement to adopt that library. The main principle is to avoid manually duplicating remote data in unrelated global stores.

5. Keep business logic outside presentation components

A component should primarily describe what the user sees and can do. Nontrivial calculations, normalization, and domain rules are easier to test when extracted into plain functions.

// features/billing/model/calculateTotals.ts
export type LineItem = { priceCents: number; quantity: number };

export function calculateSubtotal(items: LineItem[]): number {
  return items.reduce((sum, item) => sum + item.priceCents * item.quantity, 0);
}
// features/billing/components/OrderSubtotal.tsx
import { calculateSubtotal, type LineItem } from '../model/calculateTotals';

export function OrderSubtotal({ items }: { items: LineItem[] }) {
  const subtotal = calculateSubtotal(items);
  return <output>{(subtotal / 100).toFixed(2)}</output>;
}

Now the calculation can be unit-tested without rendering React.

6. Create a deliberate API boundary

Avoid scattering raw fetch calls throughout UI components. Centralize transport concerns and keep feature-specific endpoints close to their owners.

// shared/api/http.ts
export async function getJson<T>(url: string): Promise<T> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }
  return (await response.json()) as T;
}
// features/analytics/api/getOverview.ts
import { getJson } from '@/shared/api/http';

type Overview = { activeUsers: number; revenueCents: number };

export const getOverview = () => getJson<Overview>('/api/analytics/overview');

The generic type parameter does not validate network responses at runtime. For untrusted external data, add schema validation (for example, with Zod) at the boundary.

7. Design components for composition

A reusable component should expose a clear interface and avoid knowing too much about the feature that uses it.

interface EmptyStateProps {
  title: string;
  description?: string;
  action?: React.ReactNode;
}

export function EmptyState({ title, description, action }: EmptyStateProps) {
  return (
    <section>
      <h2>{title}</h2>
      {description && <p>{description}</p>}
      {action}
    </section>
  );
}

Keep domain-specific components in their features. Promote them to shared/ui/ only when their API is truly generic and stable.

8. Organize routes around user workflows

Routes are natural composition points. A route should assemble the relevant feature components, handle navigation-level concerns, and avoid becoming a giant business-logic file.

Consider lazy-loading heavier routes:

import { lazy, Suspense } from 'react';

const AnalyticsPage = lazy(() => import('@/features/analytics/AnalyticsPage'));

export function AnalyticsRoute() {
  return (
    <Suspense fallback={<p>Loading analytics…</p>}>
      <AnalyticsPage />
    </Suspense>
  );
}

Code splitting can improve initial load performance, but excessive splitting may add network overhead. Measure before optimizing.

9. Test at the right boundaries

A balanced testing strategy focuses on behavior and risk:

  1. Unit tests for pure calculations, formatters, and state transitions.
  2. Component tests for user-visible interactions and accessibility.
  3. Integration tests for feature workflows with mocked network boundaries.
  4. End-to-end tests for critical paths such as login, checkout, and account updates.

Avoid tests that depend on internal implementation details. A refactor should not break tests when the observable behavior remains correct.

10. Make architecture enforceable

A folder convention that nobody follows is not much of an architecture. Add guardrails where they provide value:

  • TypeScript strict mode and consistent import aliases.
  • ESLint rules for import boundaries and circular dependencies.
  • Formatting and type checking in CI.
  • Feature ownership and review conventions.
  • Short architecture decision records for consequential choices.

Document why a boundary exists, not just where files should go.

11. Common anti-patterns

Anti-patternWhy it hurtsBetter approach
Giant components/ directoryOwnership becomes unclearGroup domain components by feature
One global store for everythingUnrelated updates become coupledChoose state tools by state category
Fetching inside every componentDuplicated loading and error logicUse feature API modules and query hooks
Cross-feature deep importsInternal refactors cause breakageExport intentional public APIs
Excessive abstractionsSimple changes require many filesAbstract repeated stable patterns
Overly broad shared utilitiesShared code accumulates domain assumptionsKeep shared modules generic
Premature microfrontendsOperational complexity increasesStart with a modular monolith

12. How the structure evolves

Early stage: Use a small number of folders and keep related code together. Don't overengineer.

Growing product: Introduce feature boundaries, shared API conventions, route-level code splitting, and a consistent test strategy.

Multiple teams: Add enforced dependency rules, public feature APIs, ownership documentation, performance budgets, and CI checks.

Very large application: Consider separate packages or independently deployed frontend units only when team autonomy, release cadence, or operational constraints justify the complexity.

A practical migration plan

You do not need to reorganize the entire codebase in one pull request.

  1. Identify one high-change feature.
  2. Move its UI, API calls, hooks, and domain logic into a feature directory.
  3. Define a small public entry point.
  4. Replace deep imports with that public API.
  5. Add tests for critical behavior.
  6. Enforce the dependency rule and repeat incrementally.

This approach keeps the app working while improving its structure over time.

Final thoughts

The goal of architecture is not to predict every future requirement. It is to make today's code easy to understand and tomorrow's changes safe to make.

A strong large-scale React structure has clear feature ownership, intentional dependency direction, appropriately scoped state, testable business logic, and just enough shared infrastructure to reduce duplication without creating new coupling.

Start simple. Make boundaries explicit. Let real change patterns guide the abstractions.