Thuta Learning
React
AdvancedWeb DevelopmentIntermediate

Production Architecture & React Compiler

ReactLesson 2735 min

What you'll walk away with

  • Explain the job of app/, features/, shared/ and services/ and the direction imports flow
  • Make other code use a feature only through its index.js public entry point
  • Combine ErrorBoundary, Suspense and lazy() so one crashing widget cannot blank the whole page
  • Know the lint, test and build quality gates and the limits of client-side env variables

Explain it simply

Explain it simply

A tiny app can keep every file in one folder. Once there are ten features and five developers, though, finding which file belongs to what gets hard, and every change seems to break something elsewhere.

Think of a shopping mall. Each shop (a feature) has its own goods and staff, and customers enter only through its front door (a public entry point). The mall provides the corridors, lighting and security (the app shell). If one shop catches fire (an error), only that shop closes, not the whole mall.

Problem → Why → Solution

The problem: an app where everything imports everything

The Dashboard below imports an internal helper file from the tasks feature and the internal store of the billing feature. When the tasks team reorganises its TaskRow folder, Dashboard breaks, yet the tasks team had no idea Dashboard depended on it.

Worse, when the billing widget throws during render because of bad data, there is no error boundary, so React unmounts the entire root and the user sees a blank white page. One widget's bug takes down the whole app.

src/pages/Dashboard.jsx
// reaching into other features' private files
import { formatDue } from '../features/tasks/components/TaskRow/helpers.js';
import { invoiceStore } from '../features/billing/store/internal.js';

export default function Dashboard() {
  // 600 lines: fetching, permissions, formatting and layout in one place
  const invoices = invoiceStore.getAll();
  return (
    <main>
      <h1>Due {formatDue(new Date())}</h1>
      <BillingWidget invoices={invoices} />  {/* throws -> blank page */}
    </main>
  );
}

Why does this happen?

Without boundaries that say "this part is offered to others, that part is private", every file becomes part of every other file's public API. On top of that, when no error boundary catches a render error, React removes the whole tree rather than keep showing broken UI. Where you place boundaries is an architectural decision.

Core concept: feature boundaries and failure boundaries

A production React app is designed around two kinds of boundary. Code boundaries decide which files may import which. Runtime boundaries decide which part of the screen is affected when something fails or is slow.

1. Group code by feature

features/tasks/ holds every component, hook, API call and test that belongs to tasks, so changing a feature means working in one folder. shared/ keeps only things that are truly generic, such as a Button used everywhere.

2. Give each feature one public entry point

features/tasks/index.js exports only what the feature offers to others. Everyone else imports from index.js, so the feature's internals can be reorganised freely. ESLint's no-restricted-imports rule can enforce this automatically.

3. Keep imports flowing one way

app/ uses features/, and features/ use shared/ and services/, never the other way round. When shared/ starts importing a feature, that code is no longer truly shared.

4. Place runtime boundaries

Wrapping each route or widget in an ErrorBoundary shows the fallback only where the crash happened. Suspense shows a fallback while code or data loads, and lazy() downloads each route's code only when it is needed.

BoundaryQuestion it answersTool
Feature folder + index.jsWho may use this code?Folder layout, no-restricted-imports
ErrorBoundaryWhat disappears when it crashes?Class component + fallback
Suspense + lazy()What shows while loading, and when is code fetched?Fallback UI + dynamic import()

You do not need all of this on day one. With around ten components, a src/components folder is fine. Split out feature folders when the pain starts: two features editing the same file at once, or a change in one file breaking an unrelated screen. Error boundaries, however, belong in place before your first production deploy.

text
Folders and import direction
----------------------------
src/
  app/        providers, router, layout   --+
  features/                                 | imports flow down only
    tasks/    index.js  <- public door      v
    billing/  index.js
  shared/     generic UI (Button, Modal), ErrorBoundary
  services/   http client, monitoring, storage adapters
Mental model: shops, front doors and firewalls
  1. One feature, one folder
  2. index.js is the only way in
  3. app/ to features/ to shared/
  4. An error boundary per route

For every new file, ask which shop it belongs in and whether other shops really need to see it.

General pattern

jsx
// features/<name>/index.js
export { default as FeaturePage } from './FeaturePage.jsx';

// app/App.jsx
const FeaturePage = lazy(() => import('../features/<name>/index.js')
  .then((m) => ({ default: m.FeaturePage })));

<ErrorBoundary fallback={<ErrorMessage />}>
  <Suspense fallback={<Spinner />}><FeaturePage /></Suspense>
</ErrorBoundary>

The feature exports from index.js, and the app shell loads it with lazy() inside two layers: ErrorBoundary and Suspense. lazy() expects a default export, so then() maps the named export onto default.

A feature entry point and the app shell

Here the folder layout is shown as real code, not just described. The block holds two files: the tasks feature's index.js and App.jsx, the app shell. App.jsx knows nothing about the files inside tasks; it lazily loads index.js and nothing else. The ErrorBoundary component itself is shown in the next section.

src/app/App.jsx
// src/features/tasks/index.js: the feature's only public entry point
export { default as TasksPage } from './TasksPage.jsx';
export { useTasks } from './useTasks.js';

// src/app/App.jsx: the shell wires features together
import { lazy, Suspense } from 'react';
import AppLayout from './AppLayout.jsx';
import { ErrorBoundary } from '../shared/ErrorBoundary.jsx';

const TasksPage = lazy(() =>
  import('../features/tasks/index.js').then((m) => ({ default: m.TasksPage })),
);

export default function App() {
  return (
    <AppLayout>
      <ErrorBoundary fallback={<p role="alert">Tasks could not be shown.</p>}>
        <Suspense fallback={<p>Loading tasks…</p>}>
          <TasksPage />
        </Suspense>
      </ErrorBoundary>
    </AppLayout>
  );
}

Code breakdown

  1. The feature's public doorexport { default as TasksPage } from './TasksPage.jsx';

    The feature re-exports, by name, the component it offers. Internal components such as TaskRow are not exported, so other features cannot come to depend on them.

  2. Load the feature on demandconst TasksPage = lazy(() =>

    lazy() calls import() only when TasksPage first renders, so the bundler splits the tasks feature into its own chunk. It must be declared at module level, outside any component.

  3. Named export to defaultimport('../features/tasks/index.js').then((m) => ({ default: m.TasksPage })),

    lazy() expects an object shaped like { default: Component }. Because index.js uses a named export, then() reshapes it.

  4. Failure boundary outside<ErrorBoundary fallback={<p role="alert">Tasks could not be shown.</p>}>

    It catches render errors below it and shows the fallback. A failed chunk download also surfaces as an error when the lazy component renders, so this boundary catches that too.

  5. Loading boundary inside<Suspense fallback={<p>Loading tasks…</p>}>

    It shows the fallback while the code downloads. Sitting inside the ErrorBoundary, both loading and failure stay confined to the tasks area.

You should see
AppLayout appears immediately, with "Loading tasks…" inside it while the tasks code downloads; then TasksPage takes its place. If TasksPage throws during render, only that area shows "Tasks could not be shown." while the layout and navigation keep working.

The ErrorBoundary and error reporting

Even in React 19, an error boundary is still written as a class component. getDerivedStateFromError switches state so the fallback renders, and componentDidCatch sends the error to a monitoring service. A boundary catches errors thrown during rendering, in lifecycle methods and in constructors. It does not catch errors in event handlers or in async code such as setTimeout callbacks and promises; handle those yourself with try/catch.

src/shared/ErrorBoundary.jsx
import { Component } from 'react';
import { logError } from '../services/monitoring.js';

export class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    logError(error, info.componentStack);
  }

  render() {
    return this.state.hasError ? this.props.fallback : this.props.children;
  }
}

Quality gates and React Compiler

Before anything merges, CI always runs three steps: lint, test and build. Lint must include eslint-plugin-react-hooks, which catches broken hook rules and wrong dependency arrays. Running the build in CI catches bad import paths nobody noticed locally.

React Compiler adds memoization automatically at build time, but it only optimises code that follows the Rules of React. The safe path is to clear the lint errors first, enable it for one part of the project following the official installation guide, and compare tests and Profiler results before and after.

package.json (scripts)
{
  "scripts": {
    "lint": "eslint .",
    "test": "vitest run",
    "build": "vite build",
    "check": "npm run lint && npm run test && npm run build"
  }
}

In real projects

In real projects

In large teams, each feature folder is owned by one team, and a CODEOWNERS file requests that team's review on every pull request touching the folder. Because of public entry points, one team can work without touching another team's internals. Errors sent from componentDidCatch go to a monitoring tool such as Sentry, tagged with the release version, so a deploy that starts producing errors is noticed right away.

Environment variables need care too. In Vite, variables prefixed with VITE_ are embedded in client code through import.meta.env, so anyone who opens the JavaScript in their browser can read them. Never put API secret keys in frontend env files; keep them on the server.

Common mistakes

Common mistakes

One error boundary around the whole app

A single boundary at the root avoids the blank page, but one small widget crashing still replaces the entire screen, navigation included, with the fallback. Give each route and each important widget its own boundary.

Turning shared/ into a junk drawer

Dropping anything of uncertain home into shared/ fills it with feature logic, and soon every feature is indirectly coupled to every other one. If only one feature uses something, keep it inside that feature's folder.

Putting secrets in VITE_ variables

A variable like VITE_STRIPE_SECRET is copied verbatim into the JavaScript bundle at build time. "The .env file is not in git, so it is safe" is wrong, because the value ends up in the build output.

Mini challenge

An API client for services/

Write createApiClient() for services/http.js so components never call fetch directly. The client handles the base URL, the auth token and JSON, and turns every HTTP error into an ApiError that carries the status. A fake fetch is provided so it runs in Node.

  • Accept fetchImpl and getToken as parameters so the client is easy to test
  • Add an Authorization: Bearer <token> header when a token exists
  • When response.ok is false, throw an ApiError with the server message, or "HTTP <status>"
  • Return get(path) and post(path, body), and build a tasks API module on top of the client
http.js
class ApiError extends Error {
  // TODO: constructor(status, message) that sets name = 'ApiError' and status
}

function createApiClient({ baseUrl, fetchImpl = fetch, getToken = () => null }) {
  async function request(path, { method = 'GET', body, signal } = {}) {
    // TODO: headers (Accept, optional Authorization, Content-Type for a body)
    // TODO: call fetchImpl(baseUrl + path, { method, headers, signal, body })
    // TODO: parse JSON (204 -> null); !res.ok -> throw ApiError
  }
  // TODO: return { get, post }
}

// TODO: tasksApi(client) -> { list(signal), create(title) }

// TODO: a fake fetch with GET/POST /api/tasks, 401 without a token,
//       404 for unknown paths; then call the client and print the results

Expected: Four lines: the task list, the newly created task, "ApiError 404 No route for /api/nope", and after the token is cleared, "ApiError 401 Please sign in".

Show hint

Response is a global in Node 22, so the fake fetch can return new Response(JSON.stringify(data), { status }). Keeping getToken as a function means each request reads the current token.

Show solution
http.js
class ApiError extends Error {
  constructor(status, message) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
  }
}

function createApiClient({ baseUrl, fetchImpl = fetch, getToken = () => null }) {
  async function request(path, { method = 'GET', body, signal } = {}) {
    const headers = { Accept: 'application/json' };
    const token = getToken();
    if (token) headers.Authorization = `Bearer ${token}`;
    if (body !== undefined) headers['Content-Type'] = 'application/json';

    const res = await fetchImpl(`${baseUrl}${path}`, {
      method,
      headers,
      signal,
      body: body === undefined ? undefined : JSON.stringify(body),
    });
    const data = res.status === 204 ? null : await res.json();
    if (!res.ok) throw new ApiError(res.status, data?.message ?? `HTTP ${res.status}`);
    return data;
  }

  return {
    get: (path, options) => request(path, options),
    post: (path, body, options) => request(path, { ...options, method: 'POST', body }),
  };
}

const tasksApi = (client) => ({
  list: (signal) => client.get('/api/tasks', { signal }),
  create: (title) => client.post('/api/tasks', { title }),
});

// A fake server so the example runs without a network.
const tasks = [{ id: 1, title: 'Write tests' }];
const json = (status, data) =>
  new Response(JSON.stringify(data), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });

async function fakeFetch(url, init) {
  const { pathname } = new URL(url);
  if (init.headers.Authorization !== 'Bearer secret') {
    return json(401, { message: 'Please sign in' });
  }
  if (pathname === '/api/tasks' && init.method === 'GET') return json(200, tasks);
  if (pathname === '/api/tasks' && init.method === 'POST') {
    const task = { id: tasks.length + 1, ...JSON.parse(init.body) };
    tasks.push(task);
    return json(201, task);
  }
  return json(404, { message: `No route for ${pathname}` });
}

async function main() {
  let token = 'secret';
  const client = createApiClient({
    baseUrl: 'https://example.test',
    fetchImpl: fakeFetch,
    getToken: () => token,
  });
  const api = tasksApi(client);

  console.log(JSON.stringify(await api.list()));
  console.log(JSON.stringify(await api.create('Ship v1')));
  try {
    await client.get('/api/nope');
  } catch (err) {
    console.log(err.name, err.status, err.message);
  }
  token = null;
  try {
    await api.list();
  } catch (err) {
    console.log(err.name, err.status, err.message);
  }
}

main();

Quick quiz 1 / 3

An error is thrown inside a button's onClick handler. Does the surrounding ErrorBoundary catch it?

Quick quiz 2 / 3

Dashboard imports '../features/billing/store/internal.js' from the billing feature. What is the best fix?

Quick quiz 3 / 3

You want to start using React Compiler in a large codebase. Which approach is the safest?

What to remember

  • Keep each feature in one folder and expose it only through index.js
  • Imports flow one way: app/ to features/ to shared/ and services/
  • Wrap routes and widgets in ErrorBoundary plus Suspense, and split code with lazy()
  • Error boundaries do not catch event handler or async errors
  • Run lint, test and build in CI, and never put secrets in VITE_ variables

React Compiler v1.0 — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Production Architecture & React Compiler | Thuta Learning