Sub topic 3
Naming conventions and colocating related files
This chapter assumes you can write React components and hooks and use TypeScript import and export. It also assumes you have seen the feature-based layout from the previous chapter, where each feature has its own folder. Here you will decide what to call files and folders, and where each file sits inside a feature.
Why names and locations matter
A new teammate who wants to change the cart list should be able to guess where it lives. Names make files searchable and predictable. Location tells the reader what else is affected by a change. If the component, its styles, and its test sit in the same folder, a change usually touches one folder. If they are scattered, every change is a scavenger hunt, and files get forgotten.
Two rules cover most of this chapter:
- Pick one naming convention per kind of file and apply it everywhere.
- Keep files that change together close together (colocation).
Choosing naming conventions
The exact choices matter less than consistency. These defaults are common in React and TypeScript projects and match the layout used in this tutorial.
| Kind of file | Convention | Example |
|---|---|---|
| Component | PascalCase, same as the component name | `CartList.tsx` |
| Hook | camelCase starting with `use` | `useCart.ts` |
| Plain module (utilities, API calls) | camelCase | `formatDate.ts`, `api.ts` |
| Test | Name of the file under test plus `.test` | `CartList.test.tsx` |
| Styles | Component name plus `.module.css` | `CartList.module.css` |
| Types-only module | `types.ts` inside the feature | `types.ts` |
| Folders | lowercase, with `-` if you need two words | `order-history/` |
Why these choices
- The file name matches the main export. If
CartList.tsxexportsCartList, search, imports, and stack traces all agree. Do not name a filecart-list.tsxand exportCartList, because then two spellings refer to one thing. - Hooks start with
use. React's rules of hooks and theeslint-plugin-react-hookslint rule depend on this prefix. A file nameduseCart.tstells you before you open it that it follows hook rules. - Tests carry the name of what they test. Sorted alphabetically,
CartList.test.tsxlands right next toCartList.tsx. - Folders are lowercase. Folder names often end up in URLs, import paths, and shell commands. Lowercase avoids the case problems described next.
Case sensitivity
macOS and Windows file systems usually ignore letter case. Linux, which most CI servers use, does not. If you import ./cartList but the file is CartList.tsx, the import works on your laptop and fails in CI. Turn on TypeScript's check for this:
{
"compilerOptions": {
"forceConsistentCasingInFileNames": true
}
}With this option, TypeScript reports an error when the same file is referred to with different casing. It is already the default in recent TypeScript versions, but writing it down makes the intent clear.
Named versus default exports
Prefer named exports (export function CartList). A named export has one official name, so editors can auto-import it and renames propagate. A default export lets every importer choose a different local name, which makes searches miss usages. Exceptions exist: React.lazy expects a module with a default export, so lazily loaded page components often use one. The code-splitting chapter covers this.
Colocating related files
Colocation means placing a file next to the code that uses it. The test for deciding is: if I delete this component, which other files should be deleted with it? Those files belong in the same place.
Inside the cart feature from the previous chapter, the component, test, and styles can sit together:
src/features/cart/components/
CartList.tsx
CartList.module.css
CartList.test.tsx
CartRow.tsxHere is a component that uses its colocated stylesheet. The import paths are short because the files are neighbors:
// src/features/cart/components/CartList.tsx
import styles from "./CartList.module.css";
type Item = { id: string; name: string; quantity: number };
type CartListProps = {
items: Item[];
};
export function CartList({ items }: CartListProps) {
if (items.length === 0) {
return <p className={styles.empty}>Your cart is empty.</p>;
}
return (
<ul className={styles.list}>
{items.map((item) => (
<li key={item.id}>
{item.name} × {item.quantity}
</li>
))}
</ul>
);
}And the test next to it, which imports the component with ./:
// src/features/cart/components/CartList.test.tsx
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { CartList } from "./CartList";
describe("CartList", () => {
it("shows a message when the cart is empty", () => {
render(<CartList items={[]} />);
expect(screen.getByText("Your cart is empty.")).toBeTruthy();
});
it("lists each item with its quantity", () => {
render(<CartList items={[{ id: "1", name: "Tea", quantity: 2 }]} />);
expect(screen.getByText("Tea × 2")).toBeTruthy();
});
});This test assumes Vitest with a DOM environment such as jsdom. Where tests live in general, and what they should cover, is the subject of a later chapter. For now, the point is that the test file's location follows the same colocation rule.
Colocate by distance of use
A useful way to apply the rule is to place a file at the lowest level that contains all of its users.
- Used by one component only: put it beside that component (a small
CartRow.tsx, a style file, a helper that onlyCartListcalls). - Used by several components in one feature: put it at the feature level (
features/cart/types.ts,features/cart/hooks/). - Used by more than one feature: move it to
shared/.
Start low and promote a file only when a second user appears. Moving a file up is a small change. Moving a file down after many features depend on it is harder, because you must untangle who really needs it.
Common mistakes
- Many files named
index.tsorindex.tsx. If every component folder has anindex.tsx, your editor tabs all read "index.tsx" and search results are ambiguous. Reserveindex.tsfor a feature's public entry point, covered in the public API chapter. - Mixed conventions. Having
useCart.tsnext touse-orders.tsforces people to remember which feature does what. Write the table above (or your own version) in your contributing guide and enforce it in review or with a lint rule. - Generic names.
utils.ts,helpers.ts, andcommon.tsgrow without limit because nothing is out of scope for them. Name files for what they do:formatDate.ts,calculateTotal.ts. - Types separated from their users. A top-level
types/folder holding every type in the app moves types away from the code that changes them. Keep a feature's types in that feature. - Renaming with a plain move. On a case-insensitive file system, renaming
cartlist.tsxtoCartList.tsxmay not register in Git. Usegit mv, and checkgit statusshows the rename.
Summary of the working model
Name each file after its main export, and use a pattern a person can guess: PascalCase.tsx for components, useX.ts for hooks, X.test.tsx for tests. Put every file next to its closest user, and promote it upward only when another user appears. These rules are cheap to follow when the project is small. They are expensive to introduce later, which is why you set them early and write them down.
Exercise
Your cart feature has a formatPrice.ts helper that only CartRow.tsx uses. A week later, the orders feature also needs it. Where should the file live at each stage, and what is the risk of putting it in shared/ on day one?
Show answer
At first, put formatPrice.ts next to CartRow.tsx (or at the cart feature level), because only one component uses it. When the orders feature needs it, it now has users in two features, so move it to shared/lib/ and update both imports. Putting it in shared/ on day one risks filling shared/ with code that only one place uses, which makes shared code harder to understand and change, since people assume anything shared has many dependents.
Exercise
A file is named cartList.tsx and exports CartList. It imports fine on a Mac but the CI build on Linux reports "Cannot find module './CartList'". What is the cause, and what two changes prevent it?
Show answer
Another file imports ./CartList, but the file on disk is cartList.tsx. macOS ignores letter case, so it resolves the import, while Linux does not. Rename the file to CartList.tsx with git mv so the file name matches its export and the import, and set forceConsistentCasingInFileNames to true in tsconfig.json so TypeScript reports inconsistent casing before CI does.