| Common TypeScript Errors in React :👈 | 👉:How to Decide When to Split a Component |
How to Structure a React Project |
How to Structure a React Project
1. Introduction
React project structure defines how application files, components, pages, services, Hooks, styles, utilities and other resources are organized.
A good project structure helps developers:
- Maintain code easily as the application grows.
- Reuse components and business logic.
- Separate UI, business logic and API communication.
- Work collaboratively with other developers.
- Write unit tests more easily.
- Find and fix bugs faster.
- Avoid unnecessary dependencies between modules.
There is no single mandatory folder structure in React. The right approach depends on the application's size, complexity and team requirements.
2. Basic React Project Structure
For a small React application, a simple structure is sufficient.
my-react-app/
│
├── public/
│ └── favicon.ico
│
├── src/
│ ├── assets/
│ │ ├── images/
│ │ └── icons/
│ │
│ ├── components/
│ │ ├── Header.tsx
│ │ ├── Footer.tsx
│ │ └── Button.tsx
│ │
│ ├── pages/
│ │ ├── Home.tsx
│ │ └── About.tsx
│ │
│ ├── hooks/
│ │ └── useCounter.ts
│ │
│ ├── services/
│ │ └── api.ts
│ │
│ ├── utils/
│ │ └── formatDate.ts
│ │
│ ├── types/
│ │ └── index.ts
│ │
│ ├── App.tsx
│ └── main.tsx
│
├── package.json
├── tsconfig.json
└── vite.config.ts
This structure is suitable for small applications with a limited number of features.
3. Understanding the Purpose of Each Folder
3.1 public/
Contains static files that are served directly without being imported into JavaScript modules.
Examples:
- Favicon
- Static images that need fixed public URLs
- Robots.txt
- Other files that must retain their original names
3.2 assets/
Contains resources imported and used by React components.
assets/
├── images/
│ ├── logo.png
│ └── banner.jpg
│
├── icons/
│ └── user.svg
│
└── fonts/
└── custom-font.woff2
Example:
import logo from "../assets/images/logo.png";
function Header() {
return <img src={logo} alt="Logo" />;
}
3.3 components/
Contains reusable UI components used across different pages.
Examples:
- Header
- Footer
- Button
- Modal
- Dropdown
- Pagination
- LoadingSpinner
Example:
interface ButtonProps {
label: string;
onClick: () => void;
}
function Button({ label, onClick }: ButtonProps) {
return (
<button onClick={onClick}>
{label}
</button>
);
}
export default Button;
A reusable component should generally focus on one UI responsibility.
3.4 pages/
Contains page-level components representing application routes or screens.
Examples:
- Home
- About
- Login
- Dashboard
- Products
- UserProfile
Example:
import Button from "../components/Button";
function Home() {
return (
<div>
<h1>Welcome to Home Page</h1>
<Button
label="Get Started"
onClick={() => console.log("Started")}
/>
</div>
);
}
export default Home;
A page combines reusable components and feature-specific UI to create a complete screen.
3.5 hooks/
Contains custom React Hooks that share reusable stateful logic between components.
Examples:
- useAuth
- useFetch
- useDebounce
- useLocalStorage
- usePagination
Example:
import { useState } from "react";
function useCounter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(previous => previous + 1);
};
return { count, increment };
}
export default useCounter;
3.6 services/
Contains modules responsible for communicating with external systems, especially backend APIs.
Examples:
- Authentication API
- User API
- Product API
- Order API
- Payment API
Example:
const API_URL = "https://api.example.com";
export async function getUsers() {
const response = await fetch(`${API_URL}/users`);
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
}
For larger applications, keep API request configuration, response types and individual service functions organized separately.
3.7 utils/
Contains reusable helper functions that are not specific to React components or Hooks.
Examples:
- Date formatting
- Currency formatting
- String manipulation
- Validation helpers
- Number calculations
Example:
export function formatCurrency(amount: number): string {
return new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR"
}).format(amount);
}
3.8 types/
Contains shared TypeScript interfaces, types and other reusable type definitions.
Example:
export interface User {
id: number;
name: string;
email: string;
}
export interface Product {
id: number;
name: string;
price: number;
}
For feature-specific types, prefer keeping them close to their feature rather than placing every type in one global folder.
3.9 App.tsx
The main application component. It commonly defines the application layout, global providers and route configuration.
3.10 main.tsx
The entry point of a Vite React application. It mounts the React application into the HTML page.
Example:
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
ReactDOM.createRoot(
document.getElementById("root")!
).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
4. Feature-Based Project Structure
For medium and large React applications, a feature-based structure is often more maintainable than keeping all components, Hooks and services in separate global folders.
Instead of organizing everything by technical type, organize related files around business features.
Example:src/
│
├── app/
│ ├── App.tsx
│ ├── router.tsx
│ └── providers.tsx
│
├── features/
│ ├── auth/
│ │ ├── components/
│ │ │ ├── LoginForm.tsx
│ │ │ └── RegisterForm.tsx
│ │ │
│ │ ├── hooks/
│ │ │ └── useAuth.ts
│ │ │
│ │ ├── services/
│ │ │ └── authApi.ts
│ │ │
│ │ ├── types/
│ │ │ └── auth.types.ts
│ │ │
│ │ └── index.ts
│ │
│ ├── users/
│ │ ├── components/
│ │ │ ├── UserList.tsx
│ │ │ └── UserCard.tsx
│ │ │
│ │ ├── hooks/
│ │ │ └── useUsers.ts
│ │ │
│ │ ├── services/
│ │ │ └── userApi.ts
│ │ │
│ │ ├── types/
│ │ │ └── user.types.ts
│ │ │
│ │ └── index.ts
│ │
│ └── products/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── types/
│
├── shared/
│ ├── components/
│ │ ├── Button.tsx
│ │ ├── Modal.tsx
│ │ └── Loader.tsx
│ │
│ ├── hooks/
│ ├── utils/
│ └── types/
│
├── assets/
│ ├── images/
│ └── icons/
│
├── styles/
│ └── global.css
│
└── main.tsx
Why is this approach useful?
- All files related to a feature stay together.
- Developers can understand a feature without searching multiple unrelated folders.
- Features can evolve independently.
- Feature-specific types and services do not unnecessarily pollute global folders.
- It becomes easier to test and maintain larger applications.
5. Feature-Based vs Layer-Based Structure
There are two common ways to organize a React application.
Layer-Based Structure
Files are organized according to their technical responsibility.
src/
├── components/
├── pages/
├── hooks/
├── services/
├── types/
└── utils/
Feature-Based Structure
Files are organized according to application functionality.
src/
├── features/
│ ├── auth/
│ ├── users/
│ └── products/
│
└── shared/
├── components/
├── hooks/
└── utils/
| Aspect | Layer-Based | Feature-Based |
|---|---|---|
| Organization | By technical responsibility | By business functionality |
| Small applications | Simple and convenient | Can be unnecessary initially |
| Large applications | Folders can become crowded | Related files stay together |
| Feature ownership | Files may be spread across folders | More localized |
| Reusability | Shared folders are straightforward | Shared modules can be separated |
Recommendation: For a growing business application, use a feature-based structure with a separate shared folder for genuinely reusable components and utilities.
6. Separate UI, Business Logic and API Communication
A common mistake is writing API calls, business logic and UI rendering inside one large component.
Avoid:function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("/api/users")
.then(response => response.json())
.then(data => setUsers(data));
}, []);
return (
<div>
{users.map((user: any) => (
<p key={user.id}>{user.name}</p>
))}
</div>
);
}
As the application grows, this component becomes difficult to maintain and test.
Better structure:features/
└── users/
├── components/
│ └── UserList.tsx
├── hooks/
│ └── useUsers.ts
├── services/
│ └── userApi.ts
└── types/
└── user.types.ts
Step 1: Define the type
// user.types.ts
export interface User {
id: number;
name: string;
}
Step 2: Create the API service
// userApi.ts
import type { User } from "../types/user.types";
export async function getUsers(): Promise<User[]> {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
}
Step 3: Create a custom Hook
// useUsers.ts
import { useEffect, useState } from "react";
import { getUsers } from "../services/userApi";
import type { User } from "../types/user.types";
export function useUsers() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let active = true;
async function loadUsers() {
try {
const data = await getUsers();
if (active) {
setUsers(data);
}
} catch (error: unknown) {
if (active) {
setError(
error instanceof Error
? error.message
: "Something went wrong"
);
}
} finally {
if (active) {
setLoading(false);
}
}
}
loadUsers();
return () => {
active = false;
};
}, []);
return { users, loading, error };
}
Step 4: Create the UI component
// UserList.tsx
import { useUsers } from "../hooks/useUsers";
function UserList() {
const { users, loading, error } = useUsers();
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
export default UserList;
Now each module has a clear responsibility:
- Types: Define the data structure.
- Services: Communicate with the backend.
- Hooks: Manage reusable stateful logic.
- Components: Display the UI.
Note: The example uses an active flag to prevent state updates after cleanup. For applications requiring request cancellation, use AbortController and pass its signal to fetch. Also, add runtime validation when the API response cannot be trusted.
7. Where Should Routes Be Defined?
Keep route definitions in a dedicated file when using React Router.
Example structure:
src/
├── app/
│ ├── App.tsx
│ └── router.tsx
│
├── features/
│ ├── auth/
│ ├── users/
│ └── products/
│
└── main.tsx
router.tsx:
import { createBrowserRouter } from "react-router";
import Home from "../pages/Home";
import About from "../pages/About";
import UserList from "../features/users/components/UserList";
export const router = createBrowserRouter([
{
path: "/",
element: <Home />
},
{
path: "/about",
element: <About />
},
{
path: "/users",
element: <UserList />
}
]);
App.tsx:
import { RouterProvider } from "react-router";
import { router } from "./router";
function App() {
return <RouterProvider router={router} />;
}
export default App;
For React Router versions and setups that use react-router-dom, import the corresponding APIs from that package instead. Keep imports consistent with the installed version.
8. Where Should State Management Be Placed?
State management should be organized according to how widely the state is used.
| State Type | Recommended Location | Example |
|---|---|---|
| Component state | Inside the component | Input value, dropdown visibility |
| Shared feature state | Feature-level Hook or state module | Selected products |
| Application-wide state | App-level provider or store | Authentication, theme |
| Server state | Data-fetching library or dedicated service layer | Users, products, orders from API |
| URL state | Route parameters and query strings | Search filters, pagination |
Common state management options include:
- useState: Simple component-level state.
- useReducer: More complex state transitions.
- Context API: Sharing state across a component subtree.
- Redux Toolkit: Centralized application state management.
- Zustand: Lightweight shared state management.
- TanStack Query: Server-state fetching, caching and synchronization.
Do not introduce a global state management library when local state or a simple Context is sufficient.
9. Where Should Tests Be Placed?
Keep tests close to the code they verify, especially in feature-based projects.
features/
└── users/
├── components/
│ ├── UserList.tsx
│ └── UserList.test.tsx
│
├── hooks/
│ ├── useUsers.ts
│ └── useUsers.test.ts
│
└── services/
├── userApi.ts
└── userApi.test.ts
Common testing tools include:
- Vitest: Test runner.
- React Testing Library: Test components from the user's perspective.
- MSW: Mock API requests during tests.
- Playwright: End-to-end browser testing.
10. Common Project Structure Mistakes
- Putting everything inside components: Separate API calls, reusable logic and UI responsibilities.
- Creating too many folders too early: Start simple and introduce structure when the application needs it.
- Creating a huge common folder: Keep feature-specific code inside its feature.
- Duplicating components: Identify genuinely reusable UI elements and move them into shared components.
- Keeping all types in one file: Organize types by feature and responsibility.
- Making components too large: Break complex components into smaller, meaningful units.
- Mixing API logic with rendering: Keep API communication separate from UI presentation.
- Creating unnecessary abstractions: Do not create Hooks, services or generic components for every small piece of code.
- Using circular imports: Design clear module dependencies and avoid modules importing each other unnecessarily.
- Sharing feature internals directly: Expose only the required public functionality from a feature.
11. Recommended Structure for a Growing React Application
For a medium-to-large React application using TypeScript, the following is a practical starting point:
src/
│
├── app/
│ ├── App.tsx
│ ├── router.tsx
│ ├── providers.tsx
│ └── store.ts
│
├── features/
│ ├── auth/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ ├── types/
│ │ └── index.ts
│ │
│ ├── users/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ ├── types/
│ │ ├── tests/
│ │ └── index.ts
│ │
│ ├── products/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ ├── types/
│ │ └── index.ts
│ │
│ └── orders/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ ├── types/
│ └── index.ts
│
├── shared/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ ├── utils/
│ └── types/
│
├── assets/
│ ├── images/
│ ├── icons/
│ └── fonts/
│
├── styles/
│ └── global.css
│
└── main.tsx
This is a suggested structure, not a mandatory React convention. Add folders such as tests, store or services only when they provide a clear organizational benefit.
12. Best Practices
- Prefer feature-based organization as the application grows.
- Keep reusable components inside
shared/components. - Keep feature-specific components inside their respective feature folders.
- Separate API communication from UI components.
- Use TypeScript interfaces and types to define application data.
- Keep state close to the components that use it.
- Use lazy loading for suitable route-level components.
- Keep tests near the code they verify.
- Use clear and consistent naming conventions.
- Keep module dependencies simple and avoid circular imports.
13. Interview Questions and Answers
Q1. What is the purpose of a React project structure?
It organizes application code into logical modules, making the application easier to maintain, test, reuse and scale.
Q2. What is the difference between components and pages?
Components are reusable UI building blocks, whereas pages represent complete application screens or routes and combine components to create those screens.
Q3. What is a feature-based folder structure?
It organizes files according to business functionality. For example, authentication-related components, Hooks, services and types are kept inside an auth feature folder.
Q4. Why should API calls be separated from components?
It separates backend communication from UI rendering, improves reusability and makes API logic easier to test and maintain.
Q5. What is the purpose of a shared folder?
It contains reusable components, Hooks, utilities and types that are genuinely used by multiple features.
Q6. Where should custom Hooks be placed?
Feature-specific Hooks should generally be placed inside their feature folder. Hooks used across multiple features can be placed in a shared Hooks folder.
Q7. Where should TypeScript interfaces be placed?
Feature-specific interfaces should stay close to their feature. Shared interfaces can be placed in a shared types folder.
Q8. Should every React application use Redux?
No. Use local state, Context or a state management library according to the application's actual state management requirements.
Q9. What is the difference between layer-based and feature-based structures?
Layer-based structures organize files by technical responsibility, such as components and services. Feature-based structures organize related files by business functionality, such as users and products.
Q10. How would you structure a large enterprise React application?
I would generally use feature-based organization with separate application configuration, shared components, feature-specific services, Hooks and types, centralized routing where appropriate, and dedicated testing. I would also establish clear module boundaries and avoid unnecessary cross-feature dependencies.
14. Key Takeaways
- React does not enforce a specific project structure.
- Small applications can start with a simple layer-based structure.
- Growing applications benefit from feature-based organization.
- Keep UI components, business logic and API communication separated where useful.
- Keep shared code genuinely reusable rather than moving everything into common folders.
- Organize types, tests and state management according to feature responsibilities.
- Choose a structure that makes the application easier to understand, test and maintain.
Golden Rule: Organize a React project around its features and responsibilities. Keep related code together, share only what is genuinely reusable, and introduce additional architectural complexity only when the application needs it.
| Common TypeScript Errors in React :👈 | 👉:How to Decide When to Split a Component |
Comments and Discussion