Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 132 ยท Routing and Apps

App Architecture and Project Structure

Organize a growing React app - feature folders, layers, shared UI, a data layer, state placement, environment config, error and loading conventions, monorepos and design systems.

A React app with five components can live in one file. A React app with five hundred components cannot, and the way you split it up decides whether new features take an afternoon or a week. React itself has no opinion about folders, routing, data fetching or where state should live. That freedom is great for small projects and dangerous for large ones: without a plan, every developer invents a new place for new code, and the codebase slowly turns into a maze.

This lesson gives you a plan. You will learn how to group code by feature, how to separate layers (UI, logic, data), where each kind of state belongs, how to handle configuration, and how to make loading and error handling look the same everywhere. The examples run in one file, so we mark each "file" with a comment such as // features/cart/index.js. In a real project those are separate files.

There is no single correct structure. What matters is that the rules are few, written down, and enforced (by code review or an ESLint import rule). Treat everything below as a starting point you adapt to your team.

Start small, then split by reason

Do not create thirty folders on day one. A good progression looks like this:

  1. One file, while the app is a prototype.
  2. Components next to their styles and tests, once files get long. A Button folder holds Button.jsx, Button.css and Button.test.jsx.
  3. Folders by feature when several people work in the app and screens start to share logic.
  4. Packages in a monorepo when several apps (a customer site, an admin panel) must share a design system or API client.

Move to the next step when the current one hurts, not before. A useful signal: if adding a feature means editing files in five unrelated folders, your structure is organized by file type instead of by purpose.

Group by feature, not by file type

The classic beginner layout groups by file type:

TEXT
src/
  components/   Cart.jsx  ProductCard.jsx  LoginForm.jsx  ...
  hooks/        useCart.js  useAuth.js  ...
  utils/        formatPrice.js  validateEmail.js  ...
  api/          cart.js  auth.js  products.js

It works for a while, but "the cart" is now scattered over four folders, and nothing tells you which utils are used by which part of the app. The feature layout keeps everything about one capability together:

TEXT
src/
  app/                 the shell: providers, router, global layout
  features/
    cart/
      CartPage.jsx
      CartBadge.jsx
      useCart.js
      cart-api.js
      cart-logic.js    pure functions (totals, discounts)
      cart.test.js
      index.js         the public API of the feature
    auth/
    products/
  shared/              code with no business knowledge
    ui/                Button, Dialog, Field, Spinner
    hooks/             useDebounce, useMediaQuery
    lib/               formatPrice, http client

The key idea is index.js: the public door of a feature. Other features may import from features/cart (which resolves to index.js) but never from features/cart/cart-logic.js. Everything behind the door can be renamed, split or rewritten without touching the rest of the app. The next example imitates this inside one file. The app only uses what the cart "exports".

A feature with one public door

Notice that addItem and totalOf are plain functions with no React in them. Business rules written as pure functions are the easiest code in your app to test (see Testing Hooks, Reducers and Custom Logic) and to reuse.

To enforce the public door, add an ESLint rule such as no-restricted-imports (or the import/no-internal-modules rule) that forbids paths like features/*/*. Rules that a tool checks survive team growth; rules that only live in a wiki do not.

Think in layers

Inside a feature, code falls into three layers. Keep the dependency arrows pointing one way:

TEXT
UI components  ->  hooks (logic + state)  ->  data layer (API clients)
  • UI components render JSX and handle user events. They should know nothing about URLs, headers or response shapes.
  • Hooks hold state and behaviour: useCart, useProducts, useCheckout. They call the data layer and give the UI plain values and functions.
  • The data layer is the only code that talks to the network or storage. It turns raw responses into the shapes your app wants (dates parsed, snake_case renamed, errors normalized).

The payoff is replaceability. When the backend changes from REST to GraphQL, only the data layer changes. When a designer asks for a new look, only components change. When you add caching with a library like TanStack Query (see Caching and Server State), it slots into the hook layer.

Three layers, one direction

Look at what BookList receives: clean { id, title, price } objects. The ugly book_id and price_cents never leave the data layer. That is also why BookList is trivial to show in a design tool or a test with fake data.

Presentational and container components

A related habit: split a screen into a container that fetches and wires things (BooksPage) and presentational components that only turn props into markup (BookList). Hooks made this split less necessary than it was in the class-component era, but it is still a good default for screens, because presentational pieces are easy to reuse and test.

Shared UI and the "no business knowledge" rule

Everything in shared/ must be usable without knowing what your product does. A Button, Dialog, Field or useDebounce belongs there. A PriceTag that formats your currency rules and discount badges does not: put it in the feature that owns the rule.

Two checks keep shared/ clean:

  • Dependency direction: shared never imports from features, and a feature never imports another feature's internals. Features may import shared; the app shell may import features.
  • Rule of three: copy code once, wait for the third copy before extracting a shared component. Early abstractions guess wrong, and a wrong shared component is more expensive than duplicated code.

Where should state live?

State placement is the architecture decision beginners get wrong most often. Walk this list from top to bottom and stop at the first match:

Kind of state Where it belongs Example
Needed by one component only useState in that component Is the menu open?
Needed by a few nearby components Lifted to their closest common parent Selected tab of a panel
Part of the URL The router (path, search params) Current page, filters, sort order
Data owned by the server A server-state cache (or your data hook) Products, orders, profile
Needed by many distant components Context or a small store Theme, signed-in user, cart
Form input in progress The form (controlled or uncontrolled) Draft of a comment

Two rules follow. First, do not copy server data into global state; keep one source of truth and let a cache refetch it. Second, put in the URL anything a user may want to bookmark or share: filters and sorting belong in search parameters, not in a hidden useState. See Choosing State Structure and State Management Options for the deep dive.

Environment configuration

Your app runs in several places: your laptop, a preview deployment, production. Differences such as the API address belong in environment variables, read in exactly one module that validates them and exports a typed, frozen object. In a Vite project, public values are exposed through import.meta.env, and only names starting with VITE_ reach the browser. Next.js uses NEXT_PUBLIC_.

TEXT
# .env.development   (never commit real secrets)
VITE_API_URL=http://localhost:8000
VITE_FEATURE_FLAGS=search,beta-banner
JavaScript
// src/shared/lib/config.js  (read-only sketch: needs a build tool)
export const config = Object.freeze({
  apiUrl: import.meta.env.VITE_API_URL,
  isProduction: import.meta.env.MODE === 'production',
});

Anything in a browser bundle is public. A "secret" API key placed in VITE_... or NEXT_PUBLIC_... can be read by every visitor. Secrets belong on a server; the browser should call your server, which holds them.

The editor cannot read .env files, so the next example passes a plain object to the same kind of validating function. The point is the pattern: fail early with a clear message instead of discovering undefined in a network request.

One validated config module

One convention for loading and errors

Every screen that fetches data has the same four situations: loading, failed, empty and loaded. If each developer handles them differently, users see inconsistent spinners and developers copy bugs. Pick one shape and use it everywhere. A popular choice is a small status object returned by every data hook, plus one component that renders the right state:

A shared Async view

Wait a moment after the run: "Tags" first shows the error with a Try again button, and pressing it loads the tags. Every screen that uses AsyncView gets the same wording, the same retry button, and the same accessibility (role="alert" announces the failure to screen readers).

For failures you cannot predict (a bug in rendering), add error boundaries at a few strategic places: around the whole app, around each route, and around risky widgets. For loading in frameworks or with use, see use() and Suspense.

A tiny design system

A design system is the shared UI layer taken seriously: tokens (colors, spacing, type sizes), primitive components that use them, and documentation. Even a small one pays off, because buttons look and behave the same everywhere. The trick is that components accept variants (tone="danger") instead of raw styles, so changing the brand means editing tokens in one place.

Tokens, variants and a card

Real design systems add keyboard handling, focus management, theming and docs (often through Storybook), but the structure is exactly this. See Component Design and Styling in React for more.

Monorepos and shared packages

When you have more than one app (say web, admin and a mobile app) a monorepo keeps them in one repository with shared packages:

TEXT
apps/
  web/            customer site
  admin/          back office
packages/
  ui/             the design system (Button, Dialog, ...)
  api-client/     typed functions for your backend
  config/         shared ESLint and TypeScript settings

Tools such as pnpm workspaces, Turborepo or Nx link packages together and cache builds. The dependency rule from before still holds at package level: apps depend on packages, packages never depend on apps, and ui must not know about your business. Start with a single app; reach for a monorepo when you really have a second consumer.

Common mistakes

  • Deep relative imports such as ../../../shared/ui/Button. Configure path aliases (@/shared/ui/Button) in your bundler.
  • Barrel files everywhere. An index.js per feature is good. An index.js in every tiny folder that re-exports everything slows bundlers and creates circular imports.
  • A giant global store holding data that really belongs to one screen or to the server cache.
  • Components that fetch and render and format and validate. Split them by layer when they pass roughly 150 lines or when you find yourself wanting to reuse one half.
  • Different loading/error UI per screen. Use one AsyncView-style convention.
  • Premature monorepo or micro-frontends. Complexity you do not need is a cost you pay daily.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of grouping code by feature instead of by file type?

    A feature folder keeps components, hooks, logic and tests for one capability together. Adding or removing the feature touches one folder instead of five.
  2. 2. What is the job of a feature's index.js file?

    Restricting imports to the feature's index file lets you reorganize everything behind it without breaking the rest of the app.
  3. 3. Where should the current search filter of a product list usually live, if users should be able to share the page link?

    State that should survive a reload or be shared belongs in the URL. The router then gives every component access to it.
  4. 4. Why should the data layer convert server responses such as book_id into the app's own shapes?

    The data layer is a translation boundary. Components receive clean values, which also makes them easy to test with fake data.
  5. 5. A teammate puts an API secret in VITE_SECRET_KEY so the browser can send it. What is wrong?

    Variables exposed to the client are compiled into the JavaScript the browser downloads. Treat them as public values.

Summary

  • Start with one file and split when it hurts; group by feature once several people work in the app.
  • Give every feature a public door (index.js) and forbid imports of its internals.
  • Keep layers one-directional: UI components, then hooks, then the data layer. Write business rules as pure functions.
  • shared/ holds code with no business knowledge; extract it after the third copy, and never import features from it.
  • Place state by scope: local, lifted, URL, server cache, context or store. Do not copy server data into global state.
  • Read environment variables in one validated config module, and remember browser variables are public.
  • Use one loading, error and empty-state convention, with error boundaries for the unexpected.
  • Reach for design-system packages and monorepos only when a second consumer exists.

Next: Authentication and Authorization Patterns