JavaScript and React course Β· Module 1: React Basics
React project structure
In this lesson8
A well-organized project structure is crucial for code maintainability, easy navigation, and scalability of React applications. In this lesson, we'll look at best practices for structuring React projects and understand how to organize files and components.
Basic React project structure
Whatever the tool, a larger React project (here a Vite one) usually has a similar structure:
my-react-project/
βββ node_modules/ # Installed dependencies
βββ public/ # Publicly accessible static files
βββ src/ # Application source code
β βββ components/ # Reusable components
β βββ pages/ # Components representing entire pages
β βββ assets/ # Assets such as images, fonts, etc.
β βββ utils/ # Utility functions
β βββ services/ # Code responsible for API communication
β βββ hooks/ # Custom React hooks
β βββ context/ # React contexts
β βββ App.jsx # Main application component
β βββ main.jsx # Application entry point
βββ index.html # The HTML page the app is loaded into
βββ vite.config.js # Vite configuration
βββ .gitignore # Files ignored by Git
βββ package.json # Project info and dependencies
βββ README.md # Project documentationLet's discuss the most important directories and their purposes:
The src/ directory
The src/ directory is the heart of your React application. It contains all the logic, components, and assets. Here's how this directory is typically organized:
components/
Contains reusable components that are used in various parts of the application. There are several approaches to structuring components:
Flat structure
components/
βββ Button.jsx
βββ Button.css
βββ Header.jsx
βββ Header.css
βββ Footer.jsx
βββ Footer.cssGrouped structure (preferred for larger projects)
components/
βββ Button/
β βββ Button.jsx
β βββ Button.css
β βββ index.js
βββ Header/
β βββ Header.jsx
β βββ Header.css
β βββ index.js
βββ Footer/
βββ Footer.jsx
βββ Footer.css
βββ index.jsUsing index.js files to export components simplifies imports:
// Instead of:
import Button from './components/Button/Button';
// You can write:
import Button from './components/Button';pages/
Components representing entire pages or views in the application. In projects with routing, each file in this directory typically corresponds to a specific URL path:
pages/
βββ Home/
β βββ Home.jsx
β βββ Home.css
βββ About/
β βββ About.jsx
β βββ About.css
βββ Dashboard/
βββ Dashboard.jsx
βββ Dashboard.cssassets/
Contains all static assets used in the application:
assets/
βββ images/
β βββ logo.png
β βββ background.jpg
βββ fonts/
β βββ roboto.ttf
β βββ open-sans.ttf
βββ styles/
βββ variables.css
βββ global.cssutils/
Utility functions and tools used throughout the application:
utils/
βββ formatDate.js
βββ validation.js
βββ helpers.jsservices/
Code responsible for communicating with external APIs or services:
services/
βββ api.js # Basic API configuration
βββ userService.js # User-related queries
βββ productService.js # Product-related querieshooks/
Custom React hooks that can be used in multiple places in the application:
hooks/
βββ useLocalStorage.js
βββ useFetch.js
βββ useForm.jscontext/
React contexts used for managing global state:
context/
βββ AuthContext.js
βββ ThemeContext.js
βββ CartContext.jsOrganization by feature vs. by type
There are two main approaches to code organization:
Organization by type (shown above)
Files are grouped by their type (components, hooks, services, etc.).
Organization by feature
Files are grouped by feature or part of the application:
src/
βββ auth/
β βββ components/
β βββ hooks/
β βββ services/
β βββ context/
βββ products/
β βββ components/
β βββ hooks/
β βββ services/
β βββ utils/
βββ checkout/
βββ components/
βββ hooks/
βββ services/This structure is more scalable for large projects, especially when multiple people are working on them.
Naming conventions
Consistent naming is just as important as directory structure:
Components
- Use PascalCase:
Button.jsx,UserProfile.jsx - JSX files should have the
.jsxextension (not required, but helps with identification)
Hooks
- Always start with "use":
useLocalStorage.js,useWindowSize.js
Contexts
- Usually end with "Context":
AuthContext.js,ThemeContext.js
Services and utilities
- Use camelCase:
apiService.js,formatDate.js
Styles in React
There are several approaches to organizing styles in React:
CSS Modules
Button/
βββ Button.jsx
βββ Button.module.cssStyled Components
Button/
βββ Button.jsx # Contains styled-components definitionsSCSS/SASS
Button/
βββ Button.jsx
βββ Button.scssFolder structure best practices
In the React cosmic fleet, a well-organized folder structure is like an efficient logistics system on a spaceship - everything has its place and you can quickly find what you need. Here are proven practices for organizing React projects.
Feature-based vs Type-based organization
Two main approaches to organizing code in React projects:
Type-based organization
Files grouped by their technical role - all components together, all hooks together, etc.
src/
βββ components/
β βββ Button/
β βββ Card/
β βββ Modal/
β βββ UserProfile/
β βββ ProductCard/
β βββ ShoppingCart/
βββ hooks/
β βββ useAuth.js
β βββ useProducts.js
β βββ useCart.js
βββ services/
β βββ authService.js
β βββ productService.js
β βββ cartService.js
βββ utils/
βββ validators.js
βββ formatters.jsAdvantages:
- Simpler for small and medium projects
- Easy to understand for new developers
- Good for SPA applications without distinct modules
Disadvantages:
- In large projects, it's hard to find all files related to a single feature
- Components from different features are mixed together
- Harder to scale across teams
Feature-based organization
Files grouped by business feature - all files related to authentication together, all product-related files together, etc.
src/
βββ features/
β βββ auth/
β β βββ components/
β β β βββ LoginForm/
β β β βββ RegisterForm/
β β β βββ PasswordReset/
β β βββ hooks/
β β β βββ useAuth.js
β β β βββ useSession.js
β β βββ services/
β β β βββ authService.js
β β βββ utils/
β β β βββ validators.js
β β βββ index.js
β β
β βββ products/
β β βββ components/
β β β βββ ProductList/
β β β βββ ProductCard/
β β β βββ ProductDetails/
β β βββ hooks/
β β β βββ useProducts.js
β β β βββ useProductFilters.js
β β βββ services/
β β β βββ productService.js
β β βββ index.js
β β
β βββ cart/
β βββ components/
β β βββ ShoppingCart/
β β βββ CartItem/
β β βββ Checkout/
β βββ hooks/
β β βββ useCart.js
β βββ services/
β β βββ cartService.js
β βββ index.js
β
βββ shared/
β βββ components/
β β βββ Button/
β β βββ Modal/
β β βββ Card/
β βββ hooks/
β β βββ useLocalStorage.js
β β βββ useDebounce.js
β βββ utils/
β βββ formatDate.js
β βββ formatCurrency.js
β
βββ App.jsxAdvantages:
- Easier to scale for large projects
- All files related to a feature are in one place
- Easier for team work (different teams can work on different features)
- Easier to remove entire features
- Better for code splitting
Disadvantages:
- More complex for beginners
- Requires more thought in design
- Can lead to duplication for very small components
Naming conventions
Consistent naming is a key element of a well-organized project. In React, the following conventions apply:
Components - PascalCase
// GOOD - PascalCase
Button.jsx
UserProfile.jsx
ShoppingCart.jsx
ProductCard.jsx
// BAD - other conventions
button.jsx
user-profile.jsx
shopping_cart.jsxWhy PascalCase?
- Distinguishes React components from regular functions
- Convention adopted across the entire React ecosystem
- JSX requires PascalCase for components (custom tags)
Hooks - camelCase with "use" prefix
// GOOD - camelCase with "use"
useAuth.js
useLocalStorage.js
useWindowSize.js
useProductFilters.js
// BAD - missing "use" or wrong convention
Auth.js
local-storage.js
WindowSize.jsWhy "use" prefix?
- React requires custom hooks to start with "use"
- Allows React to validate hook rules
- Immediately communicates that it's a hook
Contexts - PascalCase with "Context" suffix
// GOOD - PascalCase with "Context"
AuthContext.js
ThemeContext.js
CartContext.js
UserPreferencesContext.js
// BAD - missing "Context" or wrong convention
auth.js
theme-context.js
Cart.jsUtils and services - camelCase
// GOOD - camelCase
formatDate.js
validateEmail.js
apiService.js
authService.js
// BAD - other conventions
FormatDate.js
validate-email.js
API_Service.jsWhere to keep different file types
Planning file locations in a project has enormous significance for its readability and scalability.
Hooks (custom hooks)
Feature-based approach:
features/
βββ auth/
β βββ hooks/
β βββ useAuth.js
β βββ useSession.js
βββ products/
βββ hooks/
βββ useProducts.js
shared/
βββ hooks/
βββ useLocalStorage.js # Shared hook
βββ useDebounce.js # Shared hook
βββ useFetch.js # Shared hookType-based approach:
hooks/
βββ useAuth.js
βββ useSession.js
βββ useProducts.js
βββ useLocalStorage.js
βββ useDebounce.js
βββ useFetch.jsUtils (utility functions)
Feature-based approach:
features/
βββ products/
β βββ utils/
β βββ formatPrice.js
β βββ filterProducts.js
βββ auth/
βββ utils/
βββ validatePassword.js
shared/
βββ utils/
βββ formatDate.js # Shared
βββ debounce.js # Shared
βββ cloneDeep.js # SharedType-based approach:
utils/
βββ formatPrice.js
βββ formatDate.js
βββ validatePassword.js
βββ filterProducts.js
βββ debounce.js
βββ cloneDeep.jsTypes (TypeScript)
If you use TypeScript, you have several options for types:
Option 1: Next to the files that use them:
components/
βββ Button/
βββ Button.tsx
βββ Button.types.ts # Types only for Button
βββ Button.styles.ts
βββ index.tsOption 2: Centralized types:
types/
βββ user.types.ts
βββ product.types.ts
βββ cart.types.ts
βββ api.types.tsOption 3: Hybrid (best):
features/
βββ products/
βββ components/
βββ types/ # Feature-specific types
β βββ product.types.ts
β βββ filter.types.ts
βββ index.ts
shared/
βββ types/ # Shared types
βββ common.types.ts
βββ api.types.tsExample project structure - best practices
Combining feature-based for main features and type-based for shared resources:
my-react-app/
βββ public/
βββ src/
β βββ features/ # Main features
β β βββ auth/
β β β βββ components/
β β β β βββ LoginForm/
β β β β β βββ LoginForm.tsx
β β β β β βββ LoginForm.styles.ts
β β β β β βββ LoginForm.test.tsx
β β β β β βββ index.ts
β β β β βββ RegisterForm/
β β β βββ hooks/
β β β β βββ useAuth.ts
β β β β βββ useSession.ts
β β β βββ services/
β β β β βββ authService.ts
β β β βββ types/
β β β β βββ auth.types.ts
β β β βββ index.ts
β β β
β β βββ products/
β β β βββ components/
β β β β βββ ProductList/
β β β β βββ ProductCard/
β β β β βββ ProductFilters/
β β β βββ hooks/
β β β β βββ useProducts.ts
β β β β βββ useProductFilters.ts
β β β βββ services/
β β β β βββ productService.ts
β β β βββ types/
β β β β βββ product.types.ts
β β β βββ index.ts
β β β
β β βββ cart/
β β βββ [similar structure]
β β
β βββ shared/ # Shared resources
β β βββ components/
β β β βββ Button/
β β β β βββ Button.tsx
β β β β βββ Button.styles.ts
β β β β βββ Button.test.tsx
β β β β βββ index.ts
β β β βββ Modal/
β β β βββ Card/
β β β βββ Layout/
β β β
β β βββ hooks/
β β β βββ useLocalStorage.ts
β β β βββ useDebounce.ts
β β β βββ useFetch.ts
β β β
β β βββ utils/
β β β βββ formatDate.ts
β β β βββ validators.ts
β β β βββ helpers.ts
β β β
β β βββ types/
β β β βββ common.types.ts
β β β βββ api.types.ts
β β β
β β βββ constants/
β β βββ routes.ts
β β βββ config.ts
β β
β βββ layouts/ # Layout components
β β βββ MainLayout/
β β βββ AuthLayout/
β β βββ DashboardLayout/
β β
β βββ pages/ # Page components (for routing)
β β βββ HomePage/
β β βββ ProductsPage/
β β βββ ProductDetailPage/
β β βββ CartPage/
β β
β βββ context/ # Global contexts
β β βββ AuthContext.tsx
β β βββ ThemeContext.tsx
β β βββ CartContext.tsx
β β
β βββ router/ # Routing configuration
β β βββ routes.tsx
β β βββ ProtectedRoute.tsx
β β
β βββ styles/ # Global styles
β β βββ globals.css
β β βββ variables.css
β β βββ reset.css
β β
β βββ App.tsx
β βββ index.tsx
β
βββ .eslintrc.js
βββ .prettierrc
βββ tsconfig.json
βββ package.json
βββ README.mdFile organization rules
- Maximum 3 levels rule
- Avoid nesting deeper than 3 levels
- If you need more, your structure is probably too complex
// GOOD - 3 levels
src/features/products/components/
// BAD - too deep
src/modules/ecommerce/features/products/ui/components/- Export through index.ts
- Every folder with a component has an index.ts
- Simplifies imports and hides implementation details
// components/Button/index.ts
export { default } from './Button';
export * from './Button.types';
// Usage
import Button from './components/Button'; // readable
// instead of
import Button from './components/Button/Button'; // verbose- Colocation - keep together what is used together
- Styles next to the component
- Tests next to the component
- Types next to the component
Button/
βββ Button.tsx # Component
βββ Button.styles.ts # Styles
βββ Button.test.tsx # Tests
βββ Button.types.ts # Types
βββ index.ts # Export- Shared vs Feature-specific
- If something is used in more than 2 places -> shared
- If something is specific to a feature -> keep it in the feature
Practical tips for project structure
Start simple - Don't over-engineer a complex structure at the beginning of a project. For a small application, type-based may suffice; only later refactor to feature-based as the project grows.
Refactor when needed - Adapt the structure as the project develops. If a folder has more than 10-15 files, consider splitting it.
Keep components small - Components should be small and focused on a single task. If a component has more than 200-300 lines, consider splitting it.
Group related files - Keep files that are closely related together. If you always edit two files together, they should probably be in the same folder.
Document - Add README.md to main directories to explain their purpose and structure.
Consistency above all - Once you choose a layout (by type, by feature, or the hybrid described above), stick to it throughout the project. The worst thing is mixing styles at random.
Tools that help with code organization
- ESLint - Helps maintain consistent code style and catch potential errors
- Prettier - Automatically formats code according to established rules
- Import sorter - Sorts imports for better readability
- Path aliases - Simplifies imports using aliases like @components, @utils
// tsconfig.json or jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@components/*": ["shared/components/*"],
"@features/*": ["features/*"],
"@utils/*": ["shared/utils/*"],
"@hooks/*": ["shared/hooks/*"]
}
}
}
// Usage
import Button from '@components/Button';
import { useAuth } from '@features/auth';
import { formatDate } from '@utils/formatDate';A well-organized project structure greatly facilitates work, especially in large teams and projects. Remember that there is no single "right" structure - the most important thing is that it is consistent, logical for your team, and scalable as the project grows.
Code for this lesson: App.jsx
import React, { useState } from 'react';
// Demonstration of Vite + React project structure
function ViteProjectDemo() {
const [activeFile, setActiveFile] = useState('App.jsx');
const fileStructure = [
{ name: 'node_modules/', type: 'folder', description: 'Installed packages' },
{ name: 'public/', type: 'folder', description: 'Static files' },
{ name: ' vite.svg', type: 'file', description: 'Vite logo' },
{ name: 'src/', type: 'folder', description: 'Source code' },
{ name: ' assets/', type: 'folder', description: 'Assets (images, fonts)' },
{ name: ' App.jsx', type: 'file', description: 'Main component', active: true },
{ name: ' App.css', type: 'file', description: 'Component styles' },
{ name: ' main.jsx', type: 'file', description: 'Entry point' },
{ name: ' index.css', type: 'file', description: 'Global styles' },
{ name: 'index.html', type: 'file', description: 'Main HTML (in the root directory!)' },
{ name: 'vite.config.js', type: 'file', description: 'Vite configuration' },
{ name: 'package.json', type: 'file', description: 'Project configuration' },
];
const fileContents = {
'App.jsx': `import { useState } from 'react'
import './App.css'
function App() {
const [count, setCount] = useState(0)
return (
<>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount(c => c + 1)}>
count is {count}
</button>
</div>
</>
)
}
export default App`,
'main.jsx': `import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(
document.getElementById('root')
).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)`,
'vite.config.js': `import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
})`,
'package.json': `{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.2.0",
"vite": "^5.0.0"
}
}`
};
return (
<div style={{
fontFamily: 'Arial, sans-serif',
maxWidth: '1000px',
margin: '0 auto',
padding: '20px'
}}>
<header style={{
background: 'linear-gradient(135deg, #61dafb 0%, #21a1f1 100%)',
padding: '30px',
borderRadius: '12px',
color: 'white',
textAlign: 'center',
marginBottom: '30px'
}}>
<h1 style={{ margin: 0, fontSize: '2rem' }}>Vite + React</h1>
<p style={{ margin: '10px 0 0 0', opacity: 0.9 }}>
Project structure and basic files
</p>
</header>
<div style={{
backgroundColor: '#1e1e1e',
borderRadius: '8px',
padding: '20px',
marginBottom: '30px',
fontFamily: 'monospace'
}}>
<div style={{ color: '#888', marginBottom: '10px' }}>Terminal:</div>
<div style={{ color: '#00ff00' }}>$ npm create vite@latest my-app -- --template react</div>
<div style={{ color: '#888', marginTop: '5px' }}>Scaffolding project in /my-app...</div>
<div style={{ color: '#00ff00', marginTop: '5px' }}>Done. Now run: cd my-app && npm install && npm run dev</div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: '20px' }}>
<div style={{
backgroundColor: '#252526',
borderRadius: '8px',
padding: '15px'
}}>
<h3 style={{ color: '#cccccc', margin: '0 0 15px 0', fontSize: '14px' }}>
EXPLORER
</h3>
{fileStructure.map((item, index) => (
<div
key={index}
onClick={() => item.type === 'file' && setActiveFile(item.name.trim())}
style={{
padding: '8px 10px',
color: item.type === 'folder' ? '#dcb67a' : '#9cdcfe',
cursor: item.type === 'file' ? 'pointer' : 'default',
backgroundColor: activeFile === item.name.trim() ? '#094771' : 'transparent',
borderRadius: '4px',
fontSize: '14px',
fontFamily: 'monospace'
}}
>
{item.type === 'folder' ? 'βΈ' : 'β’'} {item.name}
</div>
))}
</div>
<div style={{
backgroundColor: '#1e1e1e',
borderRadius: '8px',
padding: '20px'
}}>
<div style={{
color: '#888',
fontSize: '12px',
marginBottom: '10px',
borderBottom: '1px solid #333',
paddingBottom: '10px'
}}>
{activeFile}
</div>
<pre style={{
color: '#d4d4d4',
margin: 0,
fontSize: '14px',
lineHeight: '1.5',
overflow: 'auto'
}}>
{fileContents[activeFile] || '// Select a file from the list'}
</pre>
</div>
</div>
<div style={{
marginTop: '30px',
padding: '20px',
backgroundColor: '#fff3e0',
borderRadius: '8px'
}}>
<h3 style={{ color: '#e65100', marginTop: 0 }}>Startup commands</h3>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '15px' }}>
<div style={{ backgroundColor: 'white', padding: '15px', borderRadius: '8px' }}>
<code style={{ color: '#e65100' }}>npm run dev</code>
<p style={{ margin: '5px 0 0 0', fontSize: '14px', color: '#666' }}>
Starts the development server
</p>
</div>
<div style={{ backgroundColor: 'white', padding: '15px', borderRadius: '8px' }}>
<code style={{ color: '#e65100' }}>npm run build</code>
<p style={{ margin: '5px 0 0 0', fontSize: '14px', color: '#666' }}>
Builds the production version
</p>
</div>
</div>
</div>
</div>
);
}
export default function App() {
return <ViteProjectDemo />;
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the main purpose of the src/ folder in a React project?
2. In which folder are the main React source files located?
3. Where is the index.html file located in a React project created with Vite?
Hands-on tasks in the game
- Vertical ordering
Arrange the file hierarchy of a React application:
- Click in order
Arrange the React development workflow:
- Code editor
In App.jsx, create the basic structure of a component: a React import, a functional App component that returns JSX, and a default export (export default).