Colocation
Problem
Related files are scattered across distant folders: tests in /tests
, styles in /styles
, types in /types
. When working on a component, developers jump between multiple directories, struggling to find the test file or styles that belong with it. Refactoring requires updating files in multiple locations, increasing the chance of missing something.
Solution
Organize files by feature or component, keeping tests, styles, and types in the same directory as the code they support. This makes dependencies obvious, simplifies refactoring, and helps developers find everything related to a component in one place.
Example
This example shows a feature-based folder structure where all files related to a component are grouped together in the same directory.
components/
Button/
Button.tsx # Component implementation
Button.test.tsx # Tests colocated with component
Button.css # Styles specific to this component
Button.types.ts # Type definitions for this component
Card/
Card.tsx # Component implementation
Card.test.tsx # Tests colocated with component
Card.css # Styles specific to this component
Benefits
- Makes it easy to find all files related to a component in one location.
- Simplifies refactoring since all related files move together.
- Reduces context switching between distant directories.
- Makes dependencies and relationships between files immediately obvious.
- Easier to delete features completely without leaving orphaned files.
Tradeoffs
- Can create deeper directory nesting which some developers find harder to navigate.
- May complicate global search for all tests or styles across the project.
- Some build tools or conventions expect type-based folder organization.
- Can lead to inconsistent structure if not enforced with clear guidelines.
- May duplicate configuration or setup files across feature directories.