| How to Design Error Boundaries :👈 | 👉:How to Avoid Overengineering React Applications |
How to Organize a Large React Codebase |
How to Organize a Large React Codebase
1. What Does Organizing a Large React Codebase Mean?
Organizing a React codebase means arranging components, pages, hooks, services, state management, utilities and other files in a structured way so that the application remains easy to understand, maintain, test and extend.
In a small React application, keeping a few components inside the src folder may be sufficient.
However, as an application grows, it may contain:
- Hundreds of React components.
- Multiple pages and routes.
- Several API integrations.
- Shared state across different features.
- Custom Hooks and utility functions.
- Complex business logic.
- Unit and integration tests.
Without a proper structure, developers may struggle to find files, understand dependencies and safely implement new features.
2. Why Is Code Organization Important?
A well-organized React application provides several benefits:
- Maintainability: Developers can easily locate and modify code.
- Reusability: Common components and logic can be shared.
- Scalability: New features can be added without making the structure confusing.
- Team collaboration: Different developers can work on separate features.
- Testability: Components and business logic can be tested independently.
- Reduced duplication: Common functionality can be reused instead of rewritten.
- Clear responsibilities: UI, API communication and business logic remain separated.
3. Common React Project Structure Approaches
There are several ways to organize a React application. Three common approaches are:
A. Type-Based Structure
Files are grouped according to their technical responsibility.
src/
│
├── components/
├── pages/
├── hooks/
├── services/
├── utils/
├── context/
├── stores/
└── assets/
Advantages:
- Easy to understand for beginners.
- Common file types are grouped together.
- Works well for small applications.
Disadvantages:
- Large folders can contain many unrelated files.
- Files belonging to one feature may be spread across multiple folders.
- Feature-specific changes may require navigating several folders.
B. Feature-Based Structure
Files are grouped according to application features or business functionality.
src/
│
├── features/
│ ├── products/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ ├── pages/
│ │ └── types/
│ │
│ ├── orders/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── pages/
│ │
│ └── users/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── pages/
Advantages:
- Related files stay together.
- Easy to understand feature responsibilities.
- Supports independent feature development.
- Suitable for large applications.
Disadvantages:
- Some shared components and utilities need a common location.
- Feature boundaries must be designed carefully.
- Similar folder structures may be repeated across features.
C. Hybrid Structure
A hybrid structure combines feature-based organization with shared technical folders.
Feature-specific code stays inside its feature, while reusable application-wide functionality stays in shared folders.
This is a practical approach for many medium and large React applications.
4. Recommended Folder Structure for a Large React Application
Consider the following e-commerce application structure:
src/
│
├── app/
│ ├── App.jsx
│ ├── routes.jsx
│ ├── providers.jsx
│ └── store.js
│
├── features/
│ │
│ ├── products/
│ │ ├── components/
│ │ │ ├── ProductCard.jsx
│ │ │ ├── ProductList.jsx
│ │ │ └── ProductFilter.jsx
│ │ │
│ │ ├── pages/
│ │ │ ├── ProductsPage.jsx
│ │ │ └── ProductDetailsPage.jsx
│ │ │
│ │ ├── hooks/
│ │ │ └── useProducts.js
│ │ │
│ │ ├── services/
│ │ │ └── productService.js
│ │ │
│ │ └── types/
│ │ └── productTypes.js
│ │
│ ├── orders/
│ │ ├── components/
│ │ ├── pages/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── types/
│ │
│ ├── users/
│ │ ├── components/
│ │ ├── pages/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── types/
│ │
│ └── cart/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── store/
│
├── shared/
│ ├── components/
│ │ ├── Button.jsx
│ │ ├── Modal.jsx
│ │ ├── Loader.jsx
│ │ └── ErrorBoundary.jsx
│ │
│ ├── hooks/
│ │ ├── useDebounce.js
│ │ └── useLocalStorage.js
│ │
│ ├── utils/
│ │ ├── formatDate.js
│ │ └── formatCurrency.js
│ │
│ └── constants/
│ └── appConstants.js
│
├── services/
│ ├── apiClient.js
│ └── authService.js
│
├── assets/
│ ├── images/
│ └── icons/
│
└── styles/
This structure separates application setup, business features and reusable functionality.
5. Understand the Responsibility of Each Folder
App Folder
Contains application-level configuration and setup.
Examples:
- Application entry components.
- Route configuration.
- Global providers.
- Global state store configuration.
Features Folder
Contains business-specific functionality.
For example, a Products feature may contain:
- Product listing components.
- Product details pages.
- Product API services.
- Product-related Hooks.
- Product-specific types.
Shared Folder
Contains reusable functionality that is genuinely used by multiple features.
Examples:
- Buttons.
- Modals.
- Loading indicators.
- Common Hooks.
- Formatting utilities.
Services Folder
Contains application-wide infrastructure services, such as API clients and authentication integration.
Feature-specific API operations should normally remain inside their respective feature folders.
Assets Folder
Contains static application resources such as images and icons.
6. Organize Components Based on Their Responsibility
Do not put every component inside one common components folder.
Separate feature-specific components from reusable components.
Example:
features/
└── products/
└── components/
├── ProductCard.jsx
├── ProductList.jsx
├── ProductFilter.jsx
└── ProductSearch.jsx
shared/
└── components/
├── Button.jsx
├── Modal.jsx
├── Input.jsx
└── Loader.jsx
ProductCard: Specific to the Products feature.
Button: Reusable across multiple features.
Important: Do not move a component into the shared folder simply because it might be reused in the future. Move it when it has a genuine reuse requirement.
7. Separate UI Components from Business Logic
One of the most important principles in large React applications is keeping responsibilities separate.
For example, avoid putting API calls, filtering logic, form handling and large JSX structures inside one component.
Bad approach:
function ProductsPage() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState("");
useEffect(() => {
setLoading(true);
fetch("/api/products")
.then(response => response.json())
.then(data => {
setProducts(data);
setLoading(false);
});
}, []);
const filteredProducts = products.filter(
product => product.name
.toLowerCase()
.includes(search.toLowerCase())
);
return (
<div>
{/* Search, filtering and product rendering */}
</div>
);
}
This example combines API communication, state management, filtering and UI rendering in one component. It is acceptable as a small demonstration, but it can become difficult to maintain as the feature grows.
Better approach: Separate API communication, reusable logic and UI rendering.
API service:
// productService.js
export async function getProducts() {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error("Unable to fetch products");
}
return response.json();
}
Custom Hook:
// useProducts.js
import { useEffect, useState } from "react";
import { getProducts } from "../services/productService";
export function useProducts() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let active = true;
async function loadProducts() {
try {
const data = await getProducts();
if (active) {
setProducts(data);
}
} catch (error) {
if (active) {
setError(error);
}
} finally {
if (active) {
setLoading(false);
}
}
}
loadProducts();
return () => {
active = false;
};
}, []);
return { products, loading, error };
}
Page component:
// ProductsPage.jsx
import { useProducts } from "../hooks/useProducts";
import ProductList from "../components/ProductList";
function ProductsPage() {
const { products, loading, error } = useProducts();
if (loading) return <p>Loading products...</p>;
if (error) return <p>Unable to load products.</p>;
return <ProductList products={products} />;
}
Now each part has a clear responsibility.
Note: For production applications with more complex API caching, retries and synchronization requirements, consider using TanStack Query instead of building all server-state behavior manually with useEffect.
8. Organize API Communication Properly
Avoid writing API URLs and fetch logic repeatedly inside different components.
Create a common API client for shared configuration and keep feature-specific API operations inside their feature folders.
Example API client:
// services/apiClient.js
const API_BASE_URL = "/api";
export async function apiRequest(endpoint, options = {}) {
const response = await fetch(
`${API_BASE_URL}${endpoint}`,
options
);
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
return response.json();
}
Product service:
// features/products/services/productService.js
import { apiRequest } from "../../../services/apiClient";
export function getProducts() {
return apiRequest("/products");
}
export function getProductById(id) {
return apiRequest(`/products/${id}`);
}
Benefits:
- Centralized API configuration.
- Consistent error handling.
- Less duplicated code.
- Easier API maintenance.
- Feature-specific operations remain organized.
9. Organize State Management
Do not put all application state into a single global store.
Different types of state should be managed according to their requirements.
| State Requirement | Recommended Approach |
|---|---|
| Component-specific state | useState or useReducer |
| Simple shared application state | Context API |
| Complex shared client state | Redux Toolkit or Zustand |
| API data and caching | TanStack Query |
| Search, filters and pagination | URL state |
Example structure:
src/
│
├── features/
│ ├── cart/
│ │ └── store/
│ │ └── cartStore.js
│ │
│ ├── users/
│ │ └── context/
│ │ └── UserContext.jsx
│ │
│ └── products/
│ └── hooks/
│ └── useProducts.js
This keeps state management close to the feature that owns it when appropriate.
10. Organize Routing and Pages
For a large application, keep route configuration separate from individual page components.
Example:
// app/routes.jsx
import { createBrowserRouter } from "react-router-dom";
import HomePage from "../features/home/pages/HomePage";
import ProductsPage from "../features/products/pages/ProductsPage";
import OrdersPage from "../features/orders/pages/OrdersPage";
export const router = createBrowserRouter([
{
path: "/",
element: <HomePage />
},
{
path: "/products",
element: <ProductsPage />
},
{
path: "/orders",
element: <OrdersPage />
}
]);
Application setup:
// app/App.jsx
import { RouterProvider } from "react-router-dom";
import { router } from "./routes";
function App() {
return <RouterProvider router={router} />;
}
export default App;
For very large applications, route definitions can also be split into feature-specific route modules and combined in the application routing configuration.
11. Use Lazy Loading for Large Applications
When an application has many pages, loading every page's JavaScript immediately can increase the initial bundle size.
React supports lazy loading through React.lazy() and Suspense.
Example:
import { lazy, Suspense } from "react";
const ProductsPage = lazy(
() => import("../features/products/pages/ProductsPage")
);
const OrdersPage = lazy(
() => import("../features/orders/pages/OrdersPage")
);
function App() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<ProductsPage />
</Suspense>
);
}
Lazy loading allows the relevant component code to be loaded when needed rather than including every page in the initial JavaScript bundle.
Important: In a real application, place lazy-loaded components in their corresponding routes. The example above demonstrates the basic concept.
12. Use Index Files Carefully
Some projects use an index.js file to export multiple components from a folder.
Example:
// features/products/components/index.js
export { default as ProductCard } from "./ProductCard";
export { default as ProductList } from "./ProductList";
export { default as ProductFilter } from "./ProductFilter";
Now components can be imported using:
import {
ProductCard,
ProductList,
ProductFilter
} from "../components";
This can make imports shorter.
However, avoid creating unnecessary index files everywhere. Excessive barrel exports can make dependency relationships less obvious and sometimes complicate circular dependency debugging.
13. Organize Testing Alongside Features
Testing files should be easy to locate and maintain.
One practical approach is to keep tests close to the components or services they test.
Example:
features/
└── products/
├── components/
│ ├── ProductCard.jsx
│ └── ProductCard.test.jsx
│
├── services/
│ ├── productService.js
│ └── productService.test.js
│
└── hooks/
├── useProducts.js
└── useProducts.test.js
Tests should cover important behavior, including:
- Component rendering.
- User interactions.
- API success and failure scenarios.
- State updates.
- Business rules.
14. Define Clear Feature Boundaries
As applications grow, features may depend on one another. Poorly managed dependencies can create tightly coupled code.
For example:
products/
orders/
users/
cart/
Each feature should own its business-specific components, logic and data operations.
When another feature needs something, expose a clear public interface rather than importing deeply into its internal folders.
Example:
// features/products/index.js
export { default as ProductCard } from "./components/ProductCard";
export { getProducts } from "./services/productService";
Another feature can import from the public entry point:
import { ProductCard } from "../products";
For larger applications, document which features are allowed to depend on other features. Avoid circular dependencies and uncontrolled cross-feature imports.
15. Common Mistakes in Large React Codebases
- One huge components folder: Group feature-specific components with their features.
- Large component files: Extract meaningful child components and custom Hooks when responsibilities become difficult to manage.
- Duplicated API calls: Use common API infrastructure and appropriate server-state caching.
- Mixing business logic with UI: Separate API operations, reusable logic and presentation where it improves clarity.
- Everything in global state: Keep local state local and share only what needs to be shared.
- Unclear naming: Use descriptive names such as ProductDetailsPage and useProducts.
- Too many unnecessary abstractions: Do not create folders, components or utility layers without a genuine need.
- Uncontrolled cross-feature imports: Define clear public interfaces between features.
- Ignoring tests: Add tests for important business logic and user-facing behavior.
- Premature optimization: Measure performance before introducing complex optimization techniques.
16. Recommended Best Practices
- Prefer feature-based or hybrid folder organization for large applications.
- Keep related files together.
- Use shared folders only for genuinely reusable functionality.
- Separate API communication from presentation components.
- Keep components focused on clear responsibilities.
- Use custom Hooks to reuse stateful logic.
- Choose state management tools based on the type of state.
- Keep route configuration organized.
- Use lazy loading for appropriate large page boundaries.
- Place tests close to the code they validate.
- Use consistent naming conventions.
- Document important architecture decisions.
- Refactor incrementally instead of restructuring the entire application unnecessarily.
17. Interview Questions and Answers
Q1. How do you organize a large React application?
I prefer a feature-based or hybrid folder structure. Each feature contains its own components, pages, Hooks, services and types. Common reusable functionality is maintained in shared folders.
Q2. What is the difference between feature-based and type-based folder structures?
Type-based organization groups files by technical responsibility, such as components, Hooks and services. Feature-based organization groups files by business functionality, such as products, orders and users.
Q3. Why is feature-based architecture useful?
It keeps related files together, improves maintainability and allows teams to work on different application features more independently.
Q4. What should be placed inside a shared folder?
Components, Hooks, utilities and other functionality that are genuinely reusable across multiple features should be placed in the shared folder.
Q5. How do you avoid large React components?
Extract reusable UI into child components, move reusable stateful logic into custom Hooks, and separate API communication and business logic where appropriate.
Q6. How do you organize API calls in a large React application?
I create a common API client for shared configuration and keep feature-specific API functions inside their respective feature service folders. For server-state caching and synchronization, I consider TanStack Query.
Q7. How do you manage state in a large React application?
I use local state for component-specific requirements, Context for simple shared state, Redux Toolkit or Zustand for complex shared client state, TanStack Query for server state and URL state for shareable navigation information.
Q8. How do you improve the initial loading performance of a large React application?
I use route-level code splitting, lazy loading, appropriate caching, bundle analysis and performance profiling to identify and reduce unnecessary JavaScript loading.
Q9. How do you prevent tight coupling between features?
I define clear feature responsibilities, expose public interfaces, avoid deep imports into another feature's internal implementation and prevent circular dependencies.
Q10. Should every component have its own folder?
No. Small, closely related components can stay together. A separate folder is useful when a component has multiple supporting files, tests, styles or other related resources.
18. Final Takeaways
- Use feature-based or hybrid organization for large applications.
- Keep related components, Hooks, services and types together.
- Separate reusable application-wide functionality from feature-specific code.
- Keep API communication and UI responsibilities clear.
- Choose state management tools according to the requirement.
- Organize routes, tests and dependencies consistently.
- Avoid unnecessary abstractions and excessive folder structures.
- Refactor incrementally as the application grows.
Most important principle: A good React folder structure is not about creating more folders. It is about making responsibilities clear, keeping related code together and allowing developers to understand and change one feature without unnecessarily affecting the rest of the application.
| How to Design Error Boundaries :👈 | 👉:How to Avoid Overengineering React Applications |
Comments and Discussion