Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Part 16 / Stage 4

Structuring a growing app

Goal: Nothing in this part is a new React API - every hook, every component shape, every piece of state you'll touch below was already taught by Part 15 or earlier. This part is about where you put things once a project has outgrown one flat components/ folder: feature folders instead of type folders, colocating a component with its own hook/styles/test, the real cost barrel files carry, a decision framework for where a given piece of state should live (including the URL, Part 15's contribution), the boundary a feature's own index.js draws around its internals, a survey-only note on when useReducer stops being enough, environment variables, and the three commands that actually ship a build to a static host. Time: ~4 hours · Level: comfortable with hooks (Stage 2), fetching (Part 11), and routing (Part 15)

What you will learn

  • Feature folders (group by what a thing does) vs. type folders (group by what a thing is) - the same two files, in both shapes, proven to behave identically either way
  • Colocation: a component, its own hook, its own CSS Module, and its own test, all sitting in one folder instead of split across components/, hooks/, styles/, tests/
  • Barrel files (index.js re-exporting a folder's contents): the real convenience, and the real cost - proven directly, not asserted - of an ES module graph evaluating everything a barrel re-exports, not just the one export you asked for
  • A decision framework for where a piece of state belongs: local useState → lifted to the nearest shared parent → useContext/useReducer → the URL via useSearchParams (Part 15), in that order, each one only reached for once the one before it stops being enough
  • Module boundaries: a feature exposing a small public surface through its own index.js while keeping an internal.js nobody outside the feature is supposed to import - and the actual bug this convention prevents
  • A survey-only decision-tree note on when useContext/useReducer stop being enough for app-wide state, naming Zustand and Redux Toolkit as what comes next - not taught hands-on here, that depth is Stage 5's job
  • import.meta.env.VITE_*: Vite's convention for environment variables reaching client code, why the VITE_ prefix exists, and why a secret never belongs in one of these
  • npm run build, the dist/ folder it produces, and the one-line deploy commands for three static hosts - documentation only, nothing here gets deployed anywhere for real

A note on how this part is organised: same convention as every earlier part - every examples/ and solutions/ file here is wired into this repo's own harness/ and actually executed before being shown below. Running npx vitest run stage-4-routing-and-architecture/part-16-structuring-a-growing-app from the repo root really passes every test referenced in this file.

Topics in this part

Practice

Every exercise below pairs real .jsx/.js code with a .test.jsx that actually renders and asserts on it with Testing Library/Vitest - the same verified-output rule as every exercise in this course - except Exercise 5, which is a judgment call with no single correct code output, so its "solution" is a short written decision instead.


Exercise 1: Restructure a flat reviews feature into a feature folder

Scenario: A restaurant app's review feature is currently split by file type: components/ReviewCard.jsx, components/ReviewList.jsx, and hooks/useReviewSort.js - the exact "before" shape Section 1 argues against, now on a feature nobody has restructured yet. What to do: Starting from the three files above (write them first, in that flat shape), move all three into a single features/reviews/ folder with no behavior change at all: ReviewCard.jsx, ReviewList.jsx, useReviewSort.js, all siblings. useReviewSort(reviews, order) sorts by rating descending when order === "top-rated", or leaves the given order unchanged otherwise. ReviewList renders a <ul> of ReviewCards (<li>{author}: {rating}★</li>) in the sorted order. What to prove: write one test file that imports ReviewList from the new features/reviews/ location only (the flat version does not need to still exist once you've moved it) and asserts both the default order and "top-rated" order render reviews in the expected sequence.

Sample output (really run):

order="submitted"   -> reviews render in the order they were given
order="top-rated"    -> reviews render highest rating first

💡 Hint: examples/06_restructuring_example/ is this exact move, worked through on a different domain (restaurants, not reviews) with a hook plus two components - copy its shape, not its code.


Exercise 2: Fix a module-boundary violation - wishlist reaching into orders' internals

Scenario: A teammate's wishlist feature needs an order total, so they imported straight from orders/internal.js instead of going through orders/index.js:

// BUG: reaches past orders' public surface into its private implementation detail
import { ORDER_ROUNDING_RULE, computeRawTotal } from "../orders/internal.js";

export function WishlistTotalBroken({ amountInPaise }) {
  const raw = computeRawTotal(amountInPaise, ORDER_ROUNDING_RULE);
  return <p>Estimated total: ₹{(raw / 100).toFixed(2)}</p>;
}

This compiles and works today - but orders/internal.js was never meant to be imported from outside orders/, and nothing stops a plain relative import from doing it anyway. What to do: Write orders/internal.js (a private computeRawTotal(amountInPaise, roundingRule) plus an ORDER_ROUNDING_RULE constant) and orders/index.js (one public function, getOrderTotalLabel(amountInPaise), that calls the internal helper and formats the result - the only thing orders/ exports). Write WishlistTotalBroken (the snippet above, reaching into internal.js directly) and WishlistTotalFixed (identical output, but importing getOrderTotalLabel from orders/index.js only). What to prove: a test showing both produce the same label today, plus a comment (not a test - JavaScript has no compiler to enforce this) explaining what breaks the moment orders/internal.js ever renames computeRawTotal or changes its rounding rule's shape: WishlistTotalFixed is unaffected because it never depended on anything beyond getOrderTotalLabel's return value; WishlistTotalBroken would need an immediate matching change, in a file outside its own feature, that nothing about wishlist's own tests would catch until orders/internal.js actually changes.

Sample output (really run):

WishlistTotalBroken: ₹441.00 (42000 paise, 5% tax) - reaches into orders/internal.js
WishlistTotalFixed:  ₹441.00 (same result)          - goes through orders/index.js only

💡 Hint: examples/05_module_boundaries/'s cart/wishlist pair is this exact shape - WishlistSummary there already does this correctly; this exercise asks you to also write the broken version and explain, in a comment, the bug it's actually avoiding.


Exercise 3: Where should this state live? - a store locator's filter, tab, and URL

Scenario: A store-locator page has three pieces of state that all look similar ("something the user picked") but belong in three different places: a free-text search box that filters a list shown only on this one page, a "metro"/"all cities" tab that two sibling components both need to read, and the currently selected store - which a user should be able to bookmark, refresh, or send as a link and land right back on. What to do: Write SearchBox (local useState, filters the list by name - nobody outside this component needs that text), CityTabs + StoreList (lifted to a shared parent StoreLocatorPage, since both are siblings under it and only it), and SelectedStoreBanner (reads the selected store id from useSearchParams, not useState, as ?store=<id> - this is the one piece that must survive a refresh and be shareable as a link, the exact distinction Part 15 Section 5 made). What to prove: a test that lands directly on /stores?store=blr-01 (via MemoryRouter initialEntries) and shows the matching store's banner with no click at all - proving a useState version of this one piece of state could never do that - plus a test that typing in SearchBox narrows the list without touching the URL.

Sample output (really run):

land on "/stores?store=blr-01"  -> "Selected: Indiranagar, Bengaluru" shown immediately, no click
type "indira" in search box      -> list narrows to matching stores only, URL unchanged

💡 Hint: examples/04_where_state_lives.jsx's three stages are local → lifted → context; this exercise adds the fourth real option from Part 15, URL state, as the answer for the one piece that is neither "local" nor "shared with a sibling" but "needs to survive a reload."


Exercise 4: A feature flag read from an environment variable

Scenario: A new checkout flow should only render for builds where it's explicitly turned on - the kind of thing a .env.local on one developer's machine, or a host's deploy-time environment settings, controls without anyone editing source code. What to do: Write CheckoutFlow({ legacyTotal, newTotal }) that reads import.meta.env.VITE_FEATURE_NEW_CHECKOUT and renders newTotal's UI (<p>New checkout: ₹{newTotal}</p>) only when that var is exactly the string "true"; otherwise it renders legacyTotal's UI (<p>Checkout total: ₹{legacyTotal}</p>). Deliberately do not read any var without the VITE_ prefix for this - explain in a comment why a non-prefixed var would silently never reach this component at all. What to prove: a test that leaves the var unset and sees the legacy branch, then sets import.meta.env.VITE_FEATURE_NEW_CHECKOUT = "true" (Vitest's actual import.meta.env object, mutated directly, Section 7's technique) and sees the new branch, then unsets it again so the mutation doesn't leak into the next test.

Sample output (really run):

VITE_FEATURE_NEW_CHECKOUT unset      -> "Checkout total: ₹850"
VITE_FEATURE_NEW_CHECKOUT = "true"   -> "New checkout: ₹850"

💡 Hint: examples/07_env_vars/ApiBaseUrl.test.jsx proves the exact mechanism this exercise needs - mutate import.meta.env directly in the test, and clean it up in afterEach so it doesn't bleed into a later test.


Exercise 5: Reducer or reach for a library? - three scenarios, judged in words

Scenario: Three different teams describe their app's state and ask whether useReducer + useContext is still enough, or whether it's time to reach for a real state-management library (Section 6's decision tree names Zustand and Redux Toolkit as the next step, survey-only). What to do: For each scenario below, write a short (3-6 sentence) judgment - no code - saying which side of the line it falls on and, specifically, which signal from Section 6's table drove that call:

  1. A five-screen expense tracker where one ExpensesProvider holds a list of expenses and a running total; two screens read it, one screen writes to it.
  2. A restaurant-aggregator app where cart state, a logged-in user's profile, a live order-tracking subscription, and a multi-step checkout wizard's in-progress form all need to be read and updated from a dozen components spread across four different route trees, several of them several levels deep in <Outlet/> nesting.
  3. A dashboard where a single context value changes on every keystroke of a global search box, and every one of thirty widgets on the page subscribes to that same context and visibly lags on every keystroke. What to prove: nothing automated - this is a design judgment, not a testable function. Write your answer as solutions/ex05_reducer_or_library.md, one short paragraph per scenario.

💡 Hint: Section 6's table is built exactly to answer this - "how many unrelated features reach into the same state," "does one write cause renders far outside what actually needs to change," and "would you reach for selectors/derived-state helpers if you had them" are the three signals it names; scenario 3 is specifically about the second one.

Show the solutions for Part 16 (13 files)

solutions/ex01_reviews_feature_folder/ReviewCard.jsx

export function ReviewCard({ author, rating }) {
  return (
    <li>
      {author}: {rating}★
    </li>
  );
}

solutions/ex01_reviews_feature_folder/ReviewList.jsx

// Everything the reviews feature needs - this list, its card, and its sort
// hook - lives in this one folder. Finding or deleting this feature means
// one folder, not a components/ + hooks/ hunt across the whole app.
import { useReviewSort } from "./useReviewSort.js";
import { ReviewCard } from "./ReviewCard.jsx";

export function ReviewList({ reviews, order = "submitted" }) {
  const sorted = useReviewSort(reviews, order);
  return (
    <ul>
      {sorted.map((r) => (
        <ReviewCard key={r.id} author={r.author} rating={r.rating} />
      ))}
    </ul>
  );
}

solutions/ex01_reviews_feature_folder/ReviewList.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { ReviewList } from "./ReviewList.jsx";

const REVIEWS = [
  { id: "r1", author: "Asha", rating: 3 },
  { id: "r2", author: "Vikram", rating: 5 },
  { id: "r3", author: "Priya", rating: 4 },
];

describe("ReviewList, restructured into features/reviews/", () => {
  it("really renders reviews in the order they were given by default", () => {
    render(<ReviewList reviews={REVIEWS} />);
    const items = screen.getAllByRole("listitem").map((li) => li.textContent);
    expect(items).toEqual(["Asha: 3★", "Vikram: 5★", "Priya: 4★"]);
  });

  it("really sorts highest rating first when order is \"top-rated\"", () => {
    render(<ReviewList reviews={REVIEWS} order="top-rated" />);
    const items = screen.getAllByRole("listitem").map((li) => li.textContent);
    expect(items).toEqual(["Vikram: 5★", "Priya: 4★", "Asha: 3★"]);
  });
});

solutions/ex01_reviews_feature_folder/useReviewSort.js

// Colocated inside features/reviews/, not a shared top-level hooks/ folder -
// this hook only ever existed for this one feature's list.
export function useReviewSort(reviews, order) {
  if (order === "top-rated") {
    return [...reviews].sort((a, b) => b.rating - a.rating);
  }
  return reviews;
}

solutions/ex02_module_boundary_fix/orders/index.js

// orders' PUBLIC API - the only thing another feature should ever import.
// It is free to change how computeRawTotal/ORDER_ROUNDING_RULE work
// internally as long as this one function's return value for a given
// amount stays the same.
import { ORDER_ROUNDING_RULE, computeRawTotal } from "./internal.js";

export function getOrderTotalLabel(amountInPaise) {
  const raw = computeRawTotal(amountInPaise, ORDER_ROUNDING_RULE);
  return `₹${(raw / 100).toFixed(2)}`;
}

solutions/ex02_module_boundary_fix/orders/internal.js

// Private to the orders feature - never re-exported through orders/index.js.
// This rounding rule and raw-total shape are implementation detail, free to
// change without touching any other feature, as long as orders/index.js's
// one public function keeps returning the same kind of answer.
export const ORDER_ROUNDING_RULE = "nearest-rupee";

export function computeRawTotal(amountInPaise, roundingRule) {
  const withTax = amountInPaise * 1.05;
  if (roundingRule === "nearest-rupee") {
    return Math.round(withTax / 100) * 100;
  }
  return withTax;
}

solutions/ex02_module_boundary_fix/WishlistTotal.jsx

// BROKEN: reaches straight into orders/internal.js, a file that was never
// meant to be imported from outside orders/. It compiles and works today
// because nothing in JavaScript stops a relative import from reaching past
// a feature's own index.js - but the moment orders/internal.js renames
// computeRawTotal, changes ORDER_ROUNDING_RULE's shape, or changes what
// "raw total" even means, this file breaks immediately, and nothing in
// wishlist's own tests would catch that until orders/internal.js actually
// changes - the bug is the hidden coupling, not today's output.
import { ORDER_ROUNDING_RULE, computeRawTotal } from "./orders/internal.js";
// FIXED: crosses the boundary through orders/index.js only. If orders ever
// changes its internal rounding rule or renames computeRawTotal, this file
// never has to know or change - it only ever depended on
// getOrderTotalLabel's return value, the one promise orders' public
// surface actually makes.
import { getOrderTotalLabel } from "./orders/index.js";

export function WishlistTotalBroken({ amountInPaise }) {
  const raw = computeRawTotal(amountInPaise, ORDER_ROUNDING_RULE);
  return <p>Estimated total: ₹{(raw / 100).toFixed(2)}</p>;
}

export function WishlistTotalFixed({ amountInPaise }) {
  return <p>Estimated total: {getOrderTotalLabel(amountInPaise)}</p>;
}

solutions/ex02_module_boundary_fix/WishlistTotal.test.jsx

import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { WishlistTotalBroken, WishlistTotalFixed } from "./WishlistTotal.jsx";

describe("WishlistTotal, broken vs. fixed module-boundary crossing", () => {
  it("really produces the same total today, whichever way wishlist reached orders", () => {
    render(<WishlistTotalBroken amountInPaise={42000} />);
    expect(screen.getByText("Estimated total: ₹441.00")).toBeInTheDocument();
  });

  it("really produces the same total through the public getOrderTotalLabel only", () => {
    render(<WishlistTotalFixed amountInPaise={42000} />);
    expect(screen.getByText("Estimated total: ₹441.00")).toBeInTheDocument();
  });

  // Both pass today - that's the trap. WishlistTotalBroken only keeps
  // passing as long as orders/internal.js's computeRawTotal/
  // ORDER_ROUNDING_RULE never change shape. WishlistTotalFixed depends on
  // nothing but getOrderTotalLabel's return value - the one thing orders'
  // own public surface promises to keep stable.
});

solutions/ex03_store_locator_state/StoreLocatorPage.jsx

// Three pieces of state, three different homes - the point of this
// exercise. Each one is the smallest tool that actually fits, not a jump
// straight to the most powerful option available.
import { useState } from "react";
import { useSearchParams } from "react-router";

const STORES = [
  { id: "blr-01", name: "Indiranagar, Bengaluru", city: "Bengaluru" },
  { id: "blr-02", name: "Koramangala, Bengaluru", city: "Bengaluru" },
  { id: "mum-01", name: "Andheri, Mumbai", city: "Mumbai" },
];

// LOCAL: a free-text filter that only this page's own list reads - nobody
// else in the app needs this value, so plain useState is correct here, not
// a compromise.
export function SearchBox({ value, onChange }) {
  return (
    <input
      aria-label="Search stores"
      value={value}
      onChange={(event) => onChange(event.target.value)}
    />
  );
}

// LIFTED: CityTabs and StoreList are siblings under StoreLocatorPage, and
// only StoreLocatorPage - lifting to that one shared parent is enough, no
// context needed for two components that already share a direct parent.
export function CityTabs({ city, onChange }) {
  return (
    <nav>
      {["all", "Bengaluru", "Mumbai"].map((option) => (
        <button
          key={option}
          aria-pressed={city === option}
          onClick={() => onChange(option)}
        >
          {option === "all" ? "All cities" : option}
        </button>
      ))}
    </nav>
  );
}

export function StoreList({ stores }) {
  return (
    <ul>
      {stores.map((s) => (
        <li key={s.id}>{s.name}</li>
      ))}
    </ul>
  );
}

// URL: the selected store must survive a refresh and be shareable as a
// link - useState could never do either, so this is the one piece that
// belongs in useSearchParams, Part 15 Section 5's distinction.
export function SelectedStoreBanner() {
  const [searchParams] = useSearchParams();
  const storeId = searchParams.get("store");
  const store = STORES.find((s) => s.id === storeId);
  if (!store) return <p>No store selected</p>;
  return <p>Selected: {store.name}</p>;
}

export function StoreLocatorPage() {
  const [search, setSearch] = useState("");
  const [city, setCity] = useState("all");

  const filtered = STORES.filter((s) => {
    const matchesCity = city === "all" || s.city === city;
    const matchesSearch = s.name.toLowerCase().includes(search.toLowerCase());
    return matchesCity && matchesSearch;
  });

  return (
    <div>
      <SelectedStoreBanner />
      <SearchBox value={search} onChange={setSearch} />
      <CityTabs city={city} onChange={setCity} />
      <StoreList stores={filtered} />
    </div>
  );
}

solutions/ex03_store_locator_state/StoreLocatorPage.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { MemoryRouter } from "react-router";
import { StoreLocatorPage } from "./StoreLocatorPage.jsx";

describe("StoreLocatorPage: local vs. lifted vs. URL state", () => {
  it("really shows the selected store immediately when landing on a URL with ?store=..., no click needed", () => {
    render(
      <MemoryRouter initialEntries={["/stores?store=blr-01"]}>
        <StoreLocatorPage />
      </MemoryRouter>,
    );
    expect(screen.getByText("Selected: Indiranagar, Bengaluru")).toBeInTheDocument();
  });

  it("really shows nothing selected when no ?store= param is present", () => {
    render(
      <MemoryRouter initialEntries={["/stores"]}>
        <StoreLocatorPage />
      </MemoryRouter>,
    );
    expect(screen.getByText("No store selected")).toBeInTheDocument();
  });

  it("really narrows the list from typing in the local search box, without touching the URL", async () => {
    const user = userEvent.setup();
    render(
      <MemoryRouter initialEntries={["/stores"]}>
        <StoreLocatorPage />
      </MemoryRouter>,
    );

    expect(screen.getAllByRole("listitem")).toHaveLength(3);

    await user.type(screen.getByLabelText("Search stores"), "indira");

    const items = screen.getAllByRole("listitem");
    expect(items).toHaveLength(1);
    expect(items[0]).toHaveTextContent("Indiranagar, Bengaluru");
  });

  it("really filters by city tab, lifted to the shared parent, with no context involved", async () => {
    const user = userEvent.setup();
    render(
      <MemoryRouter initialEntries={["/stores"]}>
        <StoreLocatorPage />
      </MemoryRouter>,
    );

    await user.click(screen.getByRole("button", { name: "Mumbai" }));

    const items = screen.getAllByRole("listitem");
    expect(items).toHaveLength(1);
    expect(items[0]).toHaveTextContent("Andheri, Mumbai");
  });
});

solutions/ex04_env_feature_flag/CheckoutFlow.jsx

// Only a VITE_-prefixed var is readable here on purpose: Vite only exposes
// import.meta.env keys starting with VITE_ to client code, specifically so
// a non-prefixed var (say, a server-only secret sitting in the same .env
// file) can never silently leak into the browser bundle just because
// someone typed "env." in a component. A var like FEATURE_NEW_CHECKOUT
// (no VITE_ prefix) would read as undefined here, every time - not a bug
// to work around, the actual safety boundary doing its job.
export function CheckoutFlow({ legacyTotal, newTotal }) {
  const isNewCheckoutOn = import.meta.env.VITE_FEATURE_NEW_CHECKOUT === "true";

  if (isNewCheckoutOn) {
    return <p>New checkout: ₹{newTotal}</p>;
  }
  return <p>Checkout total: ₹{legacyTotal}</p>;
}

solutions/ex04_env_feature_flag/CheckoutFlow.test.jsx

import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { CheckoutFlow } from "./CheckoutFlow.jsx";

describe("CheckoutFlow, gated by VITE_FEATURE_NEW_CHECKOUT", () => {
  afterEach(() => {
    delete import.meta.env.VITE_FEATURE_NEW_CHECKOUT;
  });

  it("really renders the legacy flow when the flag is unset", () => {
    render(<CheckoutFlow legacyTotal={850} newTotal={850} />);
    expect(screen.getByText("Checkout total: ₹850")).toBeInTheDocument();
  });

  it("really renders the new flow only when the flag is exactly \"true\"", () => {
    import.meta.env.VITE_FEATURE_NEW_CHECKOUT = "true";
    render(<CheckoutFlow legacyTotal={850} newTotal={850} />);
    expect(screen.getByText("New checkout: ₹850")).toBeInTheDocument();
  });

  it("really stays on the legacy flow for any value other than the exact string \"true\"", () => {
    import.meta.env.VITE_FEATURE_NEW_CHECKOUT = "1";
    render(<CheckoutFlow legacyTotal={850} newTotal={850} />);
    expect(screen.getByText("Checkout total: ₹850")).toBeInTheDocument();
  });
});

solutions/ex05_reducer_or_library.md

# Exercise 5 solution: reducer or reach for a library?

No code here on purpose - this is a design judgment, the same kind Section 6's decision-tree note asks for in prose. Each answer names the specific signal from that table that drove the call.

## Scenario 1: the five-screen expense tracker
**Call: `useReducer` + `useContext` is still enough.** One provider, one list-shaped piece of state, a small and stable set of actions (add/remove/maybe edit an expense), and only three screens touching it at all - two reads, one write. None of Section 6's "reach for a library" signals are present: there's one feature's worth of state, not several unrelated ones colliding in the same provider, and a write to the expense list only matters to the two screens that already read it. Reaching for Zustand or Redux Toolkit here would add a new dependency, a new mental model, and a new thing to teach a future maintainer, to solve a coordination problem this app doesn't actually have yet.

## Scenario 2: the restaurant-aggregator app
**Call: time to reach for a library.** This is the signal Section 6 names first: multiple, mostly-unrelated pieces of state (cart, user profile, a live subscription, a multi-step form) all needing to be read and written from a dozen components spread across four separate route trees, several levels deep in nested `<Outlet/>`s. A single `useReducer` would either become one giant reducer juggling four unrelated concerns in one switch statement, or four separate contexts nested inside each other near the app's root - both are exactly the "provider pyramid" and "one reducer doing too much" smells the table calls out. A library built for this (Zustand's independent stores, or Redux Toolkit's slices) solves the "many features, many consumers, deeply nested" shape directly, which is precisely why Stage 5's state-management track rebuilds a capstone's state layer on one of them instead of scaling the Part 9/10 pattern further.
Hands-on depth on which library and how is explicitly out of scope for this part - Section 6 and `DESIGN-NOTES.md` both say so: this is a survey, the choice and the implementation belong to the Stage 5 "State management ecosystems" track.

## Scenario 3: the dashboard with thirty lagging widgets
**Call: the second named signal - a write causing renders far outside what actually changed - not necessarily a library switch by itself.** Section 6 is specific about this one: `useContext` re-renders *every* consumer on *any* change to the context value, with no built-in way to subscribe to just a slice of it. Thirty widgets all re-rendering on every keystroke of an unrelated search box is that cost showing up exactly as predicted, not a sign that `useReducer` itself is wrong. The honest first move is splitting the context so the search text and the thirty widgets' own data are no longer the same `value` object - plain Part 9/10 tools, no new dependency. If the real app's shape keeps producing this problem across many different pieces of state (not just one search box that's easy to split out), that recurring pattern - needing fine-grained, selector-style subscriptions as a matter of course - is what finally tips this toward a library, since that's precisely the problem libraries like Zustand solve with selectors baked in rather than an escape hatch bolted on.

Common mistakes

Mistake Why it is wrong Fix
Dumping every component into one flat components/ folder regardless of which feature owns it Finding or deleting one feature means hunting across every type-grouped folder (components/, hooks/, styles/) instead of one place, and that cost only grows as the app grows Group by feature (features/orders/, features/cart/), not by file type - Section 1
Adding a barrel index.js to every folder "for convenience" without weighing the cost Importing one named export through a barrel evaluates every module the barrel re-exports, not just the one you asked for - a real cost for bundle size, side effects, and circular-import risk, not a free convenience Use a barrel deliberately at a feature's own public boundary (Section 5); don't sprinkle one into folders that don't need one shared entry point - Section 3
Reaching for useContext/useReducer (or jumping straight to useState for everything) before checking whether local or lifted state already solves it Context has a real re-render cost that's wasted the moment a plain lift to a shared parent would already work, and local useState for something a sibling or a third unrelated component needs just means rebuilding the same prop-drilling Part 9 already solved Climb Section 4's table one row at a time: local → lifted → context/reducer → the URL - only move up a row once the one below has actually run out of room
Reaching into a sibling feature's internal.js instead of its index.js because "it's right there and it works" It compiles and works today, but the moment that internal file's shape changes, the reaching feature breaks immediately, outside its own tests, with no warning until the break actually happens Import only from a feature's own index.js; treat anything not re-exported there as off-limits from outside the feature - Section 5
Reaching for Zustand or Redux Toolkit the first time a context feels slightly annoying to use Section 7's signals (several unrelated features in one provider, or many consumers re-rendering on an unrelated change) are specific, learnable warning signs - "this feels like a lot of boilerplate" by itself isn't one of them Check the signal table in Section 7 before reaching for a new dependency; most apps never outgrow useReducer + useContext at all
Reading a non-VITE_-prefixed variable (or a real secret) through import.meta.env and expecting it to work, or expecting a VITE_ variable to stay private A non-prefixed var is silently undefined in client code by design; a VITE_-prefixed var is shipped straight into the built bundle for every visitor to read - neither is a safe home for a secret Prefix anything meant for client code with VITE_; keep real secrets server-side, never in a VITE_* variable - Section 8
Deploying straight from a source folder, or forgetting to run npm run build first A static host serves files as-is - it has no idea how to run JSX or bundle modules on its own Run npm run build first, then point the host's deploy command at the dist/ folder it produced - Section 9

Quick recap

  • Feature folders group files by what they're for; type folders group by what they are. Section 1 proves the same component+hook pair behaves identically in either shape - the difference shows up in how easy a feature is to find, touch, or delete, not in what it does today.
  • Colocation means a component's own hook, styles, and test sit beside it in its feature's folder, not split across shared top-level hooks//styles//tests/ folders.
  • A barrel file's convenience (one import path for a whole folder) is real, and so is its cost: importing one export through a barrel evaluates every module it re-exports, which matters for bundle size, side effects, and circular-import risk.
  • Where state lives is a climb, one rung at a time: local useState → lifted to the nearest shared parent → useContext/useReducer → the URL via useSearchParams (Part 15) for anything that must survive a refresh or be shareable as a link.
  • A feature's index.js is its public surface; an internal.js nobody outside the feature imports is how a feature stays free to change its own implementation without breaking a sibling feature that only ever depended on the public promise.
  • useContext/useReducer stop being enough when several unrelated features crowd one provider, or when one context's changes re-render far more consumers than actually need to change - Zustand and Redux Toolkit are named as the next step, survey only; hands-on depth is Stage 5's job.
  • import.meta.env.VITE_* is how Vite exposes an environment variable to client code; the VITE_ prefix is a safety boundary, not decoration - a variable without it never reaches the browser, and a variable with it is never private even if it has one.
  • npm run build produces a dist/ folder of plain static files; deploying it to Netlify, Vercel, or GitHub Pages is a one-line CLI command once that folder exists.

Checklist

  • I can explain, with Section 1's actual files, why the same component+hook pair behaving identically in two folder shapes is the point, not a surprise.
  • I colocated a component with its own hook, its own CSS Module, and its own test in one folder, the way examples/02_colocation/ does.
  • I proved for myself, by reading (or re-running) barrel.test.jsx, that importing through a barrel evaluates every module it re-exports, not just the one export I asked for.
  • I can walk a piece of state through Section 4's table and land on the right rung - local, lifted, context/reducer, or the URL - for a given scenario, and say why the rung below it wasn't enough.
  • I wrote a feature with a public index.js and a private internal.js, and can explain what actually breaks if a sibling feature imports the private file directly instead.
  • I can name the two libraries Section 7's decision tree points to next (Zustand, Redux Toolkit) and the specific signals that would make me reach for one - without having installed or used either here.
  • I read (or wrote) a component using import.meta.env.VITE_* with a sensible fallback, and can say why a non-prefixed variable never reaches it and why a VITE_-prefixed one is never a safe place for a secret.
  • I can list the exact two steps - build, then one host-specific CLI command - that take a project from source to a deployed static site.

Search the guide