Starting a React app

Frameworks, Vite, bundlers, and how to choose.

Builds on Rendering strategies.

You now know React from the reconciler up, plus the server half: rendering strategies, Server Components and a whole framework built around them. The first decision on a real project comes before any of that, though. You type one command, and that command decides your router, your data loading story, your build tool and where the app can be deployed. Getting it wrong is expensive, because those choices are hard to undo a year in.

This chapter is about that command. What React leaves to someone else, what the official recommendation is and why, how to pick between the options, and what the build tools underneath actually do. That last part is a favorite interview topic ("what does a bundler do?", "why is Vite fast in development?"), so we'll build a toy bundler to answer it properly.

The problem: React is only the view layer#

For years the default answer was npx create-react-app my-app. It gave you a webpack config, a dev server and an index.html with a <div id="root">. Then you were on your own for everything else. The React team deprecated it on February 14, 2025, and their post explains why with a list of problems every Create React App project ended up solving by hand: routing, data fetching, code splitting, and rendering strategy.

Data fetching is the easiest to feel. Here is the natural way to load data in a plain client-rendered app: each component fetches what it needs in an effect. Run it and read the timestamps in the console.

Fetching in effects creates a waterfall
import { useEffect, useState } from "react";
import { fakeFetch } from "guide-tools";

type User = { id: number; name: string };
type Book = { id: number; title: string };

const t0 = performance.now();
const at = () => Math.round(performance.now() - t0) + "ms";

function Books() {
  const [books, setBooks] = useState<Book[] | null>(null);
  useEffect(() => {
    console.log("Books starts its fetch at", at());
    fakeFetch("/books").then((b: Book[]) => {
      console.log("books arrive at", at());
      setBooks(b);
    });
  }, []);
  if (!books) return <p>Loading books…</p>;
  return <ul>{books.slice(0, 3).map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

export default function App() {
  const [user, setUser] = useState<User | null>(null);
  useEffect(() => {
    console.log("App starts its fetch at", at());
    fakeFetch("/users/1").then((u: User) => {
      console.log("user arrives at", at());
      setUser(u);
    });
  }, []);
  if (!user) return <p>Loading user…</p>;
  return (
    <>
      <h3>{user.name}'s reading list</h3>
      <Books />
    </>
  );
}
Nothing logged yet.

The books request can't start until the user request finishes, because Books doesn't exist until App has a user to render. Two 400 ms requests take about 800 ms. With five levels of nesting you'd wait for five round trips in a row. That's a waterfall: requests that could run in parallel run one after another because they're tied to rendering.

The fix is to start requests before rendering, at the place that knows where the user is going: the route. Here both requests start when the module loads (a stand-in for "when the route is matched"), and the components read them with use:

Start both requests before rendering
import { Suspense, use } from "react";
import { fakeFetch } from "guide-tools";

type User = { id: number; name: string };
type Book = { id: number; title: string };

const t0 = performance.now();
const at = () => Math.round(performance.now() - t0) + "ms";

// What a route loader does: kick off everything the page needs, in parallel.
console.log("both requests start at", at());
const userPromise: Promise<User> = fakeFetch("/users/1");
const booksPromise: Promise<Book[]> = fakeFetch("/books").then((b: Book[]) => {
  console.log("books arrive at", at());
  return b;
});

function Books() {
  const books = use(booksPromise);
  return <ul>{books.slice(0, 3).map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

function Page() {
  const user = use(userPromise);
  return (
    <>
      <h3>{user.name}'s reading list</h3>
      <Books />
    </>
  );
}

export default function App() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <Page />
    </Suspense>
  );
}
Nothing logged yet.

About 400 ms instead of 800. Nothing about React changed. What changed is who starts the fetch, and that's a routing question. So is code splitting (load the code for a page when you go to it), and so is server rendering (render the page for that URL on the server). A framework is the piece that owns the URL and therefore can coordinate code, data and rendering for it. That's the whole argument for starting with one.

The official recommendation#

As of November 2026, react.dev's "Creating a React App" page says: if you want to build a new app or website with React, start with a framework. It lists these:

# Next.js (App Router), maintained by Vercel
npx create-next-app@latest

# React Router in framework mode, maintained by Shopify
npx create-react-router@latest

# Expo, for native iOS and Android apps (and the web)
npx create-expo-app@latest

It also lists TanStack Start and RedwoodSDK as other frameworks. TanStack Start's own docs now call it stable, though react.dev's list still marks it beta, and you create a project with npx @tanstack/cli@latest create. RedwoodSDK is a smaller React framework built around Cloudflare's platform.

If none of those fit (unusual constraints, your own framework, or you just want to learn), react.dev says to build from scratch with a build tool: Vite, Parcel or Rsbuild.

# Vite with React and TypeScript
npm create vite@latest my-app -- --template react-ts

# The same, with the React Compiler already wired in
npm create vite@latest my-app -- --template react-compiler-ts

# Rsbuild
npx -y create-rsbuild@latest my-app --template react

# Parcel has no scaffolder: install it and point it at an HTML file
npm install --save-dev parcel
npx parcel src/index.html

A framework doesn't force you onto a server. Next.js can do a static export (output: "export"), React Router's framework mode has ssr: false for a pure SPA, and TanStack Start has an SPA mode. You get the router, the data loading and the code splitting, and you deploy a folder of static files to a CDN. You can turn on server rendering for the pages that need it later, which is much harder to retrofit into a hand-rolled SPA.

What each option is good at#

You learned Next.js in depth in Part 8, so here the job is comparison. These are the trade-offs you'd discuss in a design review.

Next.jsReact Router (framework)TanStack StartExpoVite + router (SPA)
RenderingRSC, SSR, static, PPR via Cache ComponentsSSR, static prerender, SPA; RSC APIs still unstableSSR, streaming, SPA; RSC experimentalNative, plus web outputClient only
Build toolTurbopack (default since Next 16)Vite pluginVite (or Rsbuild)MetroVite
Data loadingServer Components, fetch with "use cache", Server Actionsloader and action per routeRouter loaders, server functionsExpo Router, your choice of data libraryRouter loaders or a client cache like TanStack Query
StrengthMost complete RSC story, huge ecosystemWeb-standard Request/Response, runs on any JS server, easy SPA migration pathEnd-to-end type safety, URL search params as typed stateOne codebase for iOS, Android, webSimplest mental model, any static host
CostMost concepts to learn, caching model to master, best experience on VercelLess built-in caching, fewer RSC conventionsYounger, smaller ecosystemNative build pipeline, app store releasesYou own SEO, waterfalls, splitting, auth wiring

A few points that come up in interviews:

  • "Next.js locks you into Vercel." Partly true historically. Next.js 16.2 added deployment adapters, and self-hosting with next start or a standalone build has always worked. Features like image optimization and the cache need their own infrastructure when you leave Vercel. Say that precisely instead of repeating the slogan.
  • React Router is the migration path. Millions of SPAs already use React Router's declarative mode. Moving to data mode and then framework mode is incremental, which is why it's often the right pick for an existing app.
  • TanStack Start's pitch is types. Route paths, params and search params are fully typed, and a typo in a link is a compile error. If your team lives in TypeScript and the app is state-heavy, that's a real gain.
  • An SPA is still a legitimate choice for apps behind a login where SEO doesn't matter, as long as you handle data loading at the route level (next chapter) and split code per route.

How to choose#

Choosing a starting point
Native iOS or Android app?one React codebase for phones and the webExpoReact Native framework, Expo RouteryesnoPublic pages that need SEO?or a fast first paint, or server-side dataA full-stack frameworkNext.js, React Router, TanStack StartyesnoMany screens behind a login?dashboards, internal tools, editorsSPA: Vite plus a routeror a framework in SPA modeyesnoVite + React, no routerwidgets, embeds, learning, islands
Read it top to bottom and stop at the first yes. Team experience and where you deploy then pick between the options in a box, not between boxes.

The ladder handles the shape of the product. Then three practical questions decide between the options in the box:

  1. Who's on the team? A team that knows Next.js ships faster in Next.js. A team migrating a large React Router SPA should look hard at React Router's framework mode first.
  2. Where will it run? A static host or CDN only: any SPA, or a framework in static/SPA mode. A Node server, containers or a platform like Vercel or Netlify: any framework. Edge or Workers runtimes: check each framework's adapter for that platform before you commit.
  3. How much of the server do you want? Server Components move data fetching and heavy dependencies off the client, but they add a boundary to reason about (Part 7). If the app is mostly interactive client UI, a client-first framework or an SPA is less to learn.

A sensible default, configured#

My defaults, as of November 2026:

  • A public product where first load and SEO matter: npx create-next-app@latest. Accept TypeScript, ESLint and the App Router. Since Next.js 16.4 the scaffold turns on Cache Components for you.
  • An app behind a login, or a team that already uses React Router: React Router's framework mode (set ssr: false in its config for a pure SPA), or a Vite SPA with a data router if you want the smallest setup.
  • iOS and Android: npx create-expo-app@latest.

The scaffold gets you a running app. A few settings are worth making on day one, because they're cheap now and painful to retrofit:

next.config.ts
// npm install -D babel-plugin-react-compiler
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheComponents: true, // already set by create-next-app 16.4
  reactCompiler: true, // stable since Next.js 16, off by default
};

export default nextConfig;

Then, whichever tool you picked:

  1. Turn on the React Compiler now, while the codebase is small enough to fix whatever the lint rules flag (The React Compiler).
  2. Keep TypeScript strict and type-check in CI. The build doesn't check types (see the pitfalls below). Tooling and DX has the tsconfig settings worth adding.
  3. Add the React Compiler's lint rules. Vite's template lints with Oxlint, configured only for the Rules of Hooks and Fast Refresh. The Compiler's purity, refs and immutability rules come from eslint-plugin-react-hooks's recommended preset (version 7 and later), so add ESLint with it (Tooling and DX has the config).
  4. Choose the router before the first page. A framework brings its own; for a Vite SPA, read Routing first, because route-level loaders are what prevent the waterfall above.
  5. Decide which environment variables are public. Only VITE_ or NEXT_PUBLIC_ names reach the browser.
  6. Add Vitest and Testing Library before there's much to test (Testing).

A short tour of React Native and Expo#

React itself doesn't know about the DOM. The reconciler you built in Part 2 calls a renderer (a "host config") to create and update host nodes. react-dom is one renderer. React Native is another: its host components are View, Text, Image and Pressable, and they become real iOS and Android views, not HTML.

app/index.tsx (Expo Router)
import { useState } from "react";
import { Pressable, Text, View } from "react-native";

export default function Home() {
  const [count, setCount] = useState(0);
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center", gap: 12 }}>
      <Text style={{ fontSize: 20 }}>Tapped {count} times</Text>
      <Pressable onPress={() => setCount(count + 1)}>
        <Text>Tap me</Text>
      </Pressable>
    </View>
  );
}

Everything above the host layer is the React you know: components, hooks, state, context, Suspense. What changes:

  • No DOM, no CSS files. Styles are JavaScript objects, layout is Flexbox by default (flexDirection defaults to column), and text must live inside <Text>.
  • Events are onPress, not onClick, and gestures, lists (FlatList) and navigation have native-specific components.
  • The New Architecture (Fabric for rendering, JSI and TurboModules for calling native code synchronously) has been the default since React Native 0.76, so concurrent features work on native too.

Expo is to React Native what Next.js is to React: the framework. It gives you file-based routing (Expo Router, an app/ folder much like Next.js), a large set of maintained native modules, cloud builds and over-the-air updates, and web output from the same code. React's docs recommend it as the way to start a native app.

What a bundler does#

Whichever option you pick, a build tool sits underneath. Its job sounds simple: turn your src/ folder into files a browser can load fast. That breaks into four steps, and building a toy version is the quickest way to see them.

Our toy takes a "project" as a map of file names to source, written in modern ESM. It then:

  1. Resolves the module graph by following imports from the entry file.
  2. Transforms each module into something the runtime can execute (here: ESM to a tiny CommonJS, using regexes where a real tool parses an AST).
  3. Bundles the main graph into one chunk with a small runtime that implements require.
  4. Code splits: anything reached only through import() goes into its own chunk, fetched on demand.
A toy bundler
// 0. The "project": file name -> source, as you'd write it in src/.
const files = {
  "main.js": `import App from "./App.js";
App();`,
  "App.js": `import greet from "./greet.js";
import format from "./format.js";
export default function App() {
  console.log(format(greet("bundler")));
  document.querySelector("#settings").onclick = () =>
    import("./Settings.js").then((m) => m.default());
}`,
  "greet.js": `export default function greet(name) { return "hello, " + name; }`,
  "format.js": `console.log("[format.js evaluated]");
export default function format(s) { return "> " + s; }`,
  "Settings.js": `import format from "./format.js";
export default function Settings() { console.log(format("settings, loaded lazily")); }`,
};

// 1. Resolve: find static and dynamic imports, walk the graph.
function findImports(code) {
  const stat = [...code.matchAll(/import \w+ from "\.\/([\w.]+)"/g)].map((m) => m[1]);
  const dyn = [...code.matchAll(/import\("\.\/([\w.]+)"\)/g)].map((m) => m[1]);
  return { stat, dyn };
}

function collect(entry, alreadyLoaded = new Set()) {
  const modules = new Set();
  const lazy = new Set();
  const visit = (name) => {
    if (modules.has(name) || alreadyLoaded.has(name)) return;
    modules.add(name);
    const { stat, dyn } = findImports(files[name]);
    stat.forEach(visit);
    dyn.forEach((d) => lazy.add(d));
  };
  visit(entry);
  return { modules: [...modules], lazy: [...lazy] };
}

// 2. Transform: one file at a time, no knowledge of the graph.
function transform(code) {
  return code
    .replace(/import (\w+) from "\.\/([\w.]+)";?/g, 'const $1 = require("$2").default;')
    .replace(/import\("\.\/([\w.]+)"\)/g, 'loadChunk("$1")')
    .replace(/export default /g, "exports.default = ");
}

// 3. Bundle: wrap each module in a function, add a runtime.
function emitChunk(names) {
  const body = names.map(
    (n) => `  ${JSON.stringify(n)}: function (require, exports, loadChunk) {\n${transform(files[n])}\n  }`,
  );
  return "{\n" + body.join(",\n") + "\n}";
}

function runtime(mainChunk, lazyChunks) {
  const registry = { ...mainChunk };
  const cache = {};
  function require(name) {
    if (cache[name]) return cache[name];
    const exports = (cache[name] = {});
    registry[name](require, exports, loadChunk);
    return exports;
  }
  function loadChunk(name) {
    console.log("fetching the chunk for", name, "...");
    return new Promise((r) => setTimeout(r, 300)).then(() => {
      Object.assign(registry, lazyChunks[name]);
      return require(name);
    });
  }
  require("main.js");
}

// 4. Code split: each import() target gets a chunk of what main doesn't have.
const main = collect("main.js");
const lazyChunks = main.lazy.map((name) => {
  const chunk = collect(name, new Set(main.modules));
  return JSON.stringify(name) + ": " + emitChunk(chunk.modules);
});

console.log("main chunk:", main.modules.join(", "));
console.log("lazy entries:", main.lazy.join(", "));

const bundle = `(${runtime})(${emitChunk(main.modules)}, {${lazyChunks.join(", ")}});`;
console.log("--- bundle ---\n" + bundle);
new Function(bundle)(); // "Load the script."
Nothing logged yet.

Things to notice, all of which are true of real bundlers:

  • format.js is imported by App.js in the main chunk and again by Settings.js in the lazy chunk, but its log line prints once: it's evaluated once. The cache in require is why a module is a singleton within a page.
  • Settings.js is not in the main chunk. Its chunk doesn't include format.js either, because main already has it. Real bundlers do exactly this analysis, plus extracting modules shared by several lazy chunks into common chunks.
  • The transform step is per file. That's why it can run in parallel, and why it's the part people swap for faster compilers.
What a bundler does
Source modulesmain.tsxApp.tsxButton.tsxutils.tsSettings.tsximport()
Step 1 of 6

Your source: five files that import each other. Browsers can't run TSX, and in production you don't want a hundred separate requests either. That's the bundler's job.

The real build pipeline#

Real tools differ in how they do each step, but the four steps hold. Two families of tools share the work.

Compilers (the transform step) turn TSX into plain JavaScript:

  • Babel: the original, written in JavaScript, with the largest plugin ecosystem. The React Compiler ships as a Babel plugin, so Babel stays in the pipeline wherever you use it.
  • SWC: written in Rust and much faster. Next.js uses it, as do Rspack, Rsbuild and Parcel.
  • Oxc: a Rust toolchain (parser, transformer, minifier, the Oxlint linter, and a formatter). Vite 8 uses it, and @vitejs/plugin-react 6 uses it for the React Refresh transform, so Babel is no longer a dependency unless you opt into the Compiler through reactCompilerPreset.
  • tsc: the only one of these that type-checks. Everything else strips types and moves on. TypeScript 7.0 (July 8, 2026) is a native port of the compiler written in Go, typically around ten times faster than 6.0.

Bundlers (resolve, bundle, split, minify):

ToolWhat it isWhere you meet it
webpack 5The JavaScript-based veteran, with loaders and a huge plugin ecosystemOlder apps, Create React App, Next.js with --webpack
RollupESM-first bundler, popular for librariesIts plugin API is what Vite plugins use
esbuildGo, extremely fastVite 7 and earlier used it in development
RolldownRust, Rollup-compatible APIVite 8's single bundler, for dev and build
TurbopackRust, incremental, built into Next.jsDefault for next dev and next build since Next.js 16
Rspack / RsbuildRust, webpack-compatible API; Rsbuild is the ready-to-use tool on topTeams leaving webpack without rewriting config
ParcelZero-config bundler, Rust internalsSmall apps and quick prototypes

The trend is clear: the JavaScript-written tools of the 2010s are being rewritten in Rust (and tsc in Go), mainly for speed. Vite 8 (March 12, 2026) is the cleanest example: before it, Vite used esbuild in development and Rollup for production, which meant two bundlers that could disagree. Vite 8 uses Rolldown for both and Oxc as the compiler.

The dev server and hot module replacement#

The toy bundles everything up front. That's what a production build does, but it's slow to repeat on every keystroke in a large app. Vite's insight was that modern browsers understand ESM natively, so in development it doesn't bundle your source at all. The browser requests /src/main.tsx, the dev server transforms that one file and sends it, the browser sees its imports and requests those, and so on. Only the modules the current page actually imports get transformed, and only when they're requested. (Dependencies in node_modules are a different story: Vite pre-bundles them, because a library like lodash-es is hundreds of tiny files.)

Hot module replacement (HMR) builds on that. The dev server watches your files and keeps a WebSocket open to the page. When you save Button.tsx:

  1. The server re-transforms only Button.tsx and tells the page it changed.
  2. The page re-imports that one module (with a cache-busting query).
  3. The HMR runtime walks up the import graph looking for a module that accepts the update. For React components, React Refresh (the React Fast Refresh runtime) accepts it.
  4. React Refresh swaps the new component function into the existing fibers and re-renders. Hooks keep their state, because the fibers weren't thrown away.

The rules follow from the mechanism. React Refresh can only keep state if it can match old hooks to new hooks, so it computes a signature of each component's hook calls. Change that signature (add, remove or reorder a hook, or change the arguments to useState) and the component remounts with fresh state. If a file exports something that isn't a component, Refresh can't safely swap it, so the update propagates to the importers or falls back to a full reload. That's why eslint-plugin-react-refresh has an only-export-components rule.

PredictWhat survives a save

A component is on screen and you've clicked its button until it shows 5:

Counter.tsx
import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

The dev server is running with React Refresh. Predict what the button shows after each separate edit is saved: (a) change the label Count: to Clicks:; (b) change useState(0) to useState(10); (c) add const [step] = useState(1); on the line after the first useState.

Pitfalls#

Check your understanding#

Build itA module cache for the bundle runtime

The toy bundler's runtime has a require that runs each module once and caches its exports. Here's a runtime without the cache. brand.js is imported by both header.js and footer.js, so it runs twice, and the two importers get different objects. Implement createRequire so that each module runs once, every importer gets the same exports object, and a circular import doesn't recurse forever.

// Modules as a bundler emits them: already transformed, wrapped in functions.
const modules = {
  "main.js": (require, exports) => {
    const header = require("header.js").default;
    const footer = require("footer.js").default;
    exports.default = header + " / " + footer;
  },
  "header.js": (require, exports) => {
    exports.default = "header for " + require("brand.js").default.name;
  },
  "footer.js": (require, exports) => {
    exports.default = "footer for " + require("brand.js").default.name;
  },
  "brand.js": (require, exports) => {
    window.evaluations = (window.evaluations || 0) + 1;
    exports.default = { name: "Acme" };
  },
};

function createRequire(modules) {
  function require(name) {
    // TODO: run each module only once and return the same exports object.
    const exports = {};
    modules[name](require, exports);
    return exports;
  }
  return require;
}

window.createRequire = createRequire;
const result = createRequire(modules)("main.js").default;
document.body.textContent = result;
console.log(result, "| brand.js evaluated", window.evaluations, "time(s)");
Nothing logged yet.
Quick checkWhy development is fast

Why does Vite's dev server start quickly even for a large app?

Quick checkThe CRA argument

Which problem was the main reason the React team recommended frameworks over Create React App?

Explain it out loudStarting a new app

An interviewer asks: "We're starting a new React product. How would you set it up, and why not Create React App?"

Explain it out loudWhat a bundler does

"Walk me through what a bundler does, and why we still bundle when browsers support ES modules."

Interview angle

Say it in 30 seconds

React is only the view layer. Routing, data loading, code splitting and the rendering strategy all depend on the URL, so the tool that owns the URL should coordinate them. That's why react.dev recommends starting with a framework (Next.js, React Router's framework mode or Expo for native, with TanStack Start and RedwoodSDK as other options) and why Create React App was deprecated in February 2025. If you build from scratch, use Vite, Parcel or Rsbuild. Underneath, a bundler resolves the module graph, transforms each file with a compiler like SWC or Oxc, bundles chunks and splits at dynamic imports. In development Vite serves native ESM and hot-swaps modules instead.

How would you start a new React app today?

basic

Why was Create React App deprecated?

intermediate

What does a bundler actually do?

intermediate

Why is Vite's dev server fast, and how does HMR keep component state?

senior

What's the difference between Babel, SWC, Oxc and tsc?

intermediate

Next.js or React Router's framework mode: how would you decide?

senior

Recap#

  • React is the view layer. Routing, data loading, code splitting and rendering strategy all hang off the URL, so the tool that owns the URL (a framework or router) should own them.
  • react.dev recommends starting with a framework: Next.js, React Router (framework mode) or Expo, with TanStack Start and RedwoodSDK listed. From scratch means Vite, Parcel or Rsbuild. Create React App was deprecated on February 14, 2025.
  • Pick by product shape first (native, public and SEO-sensitive, app behind a login), then by team and deployment target. Frameworks can still ship as static SPAs.
  • A bundler resolves the module graph, transforms each file, bundles chunks with a runtime and splits at import(). Compilers (Babel, SWC, Oxc) do the transform and don't type-check; only tsc does.
  • Vite's dev server serves native ESM and transforms on demand; HMR swaps one module and React Refresh keeps state when a component's hook signature is unchanged.

Sources#