Popular Searches
Popular Course Categories
Popular Courses

React Project Structure

React Project Structure

React Project Setup

React Project Structure – Complete Notes

React project structure refers to the way files, folders, components, stylesheets, assets, services, routes, and tests are organized in a React application. A well-organized project makes code easier to understand, maintain, reuse, debug, test, and expand as the application grows.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. Introduction to React Project Structure

A React application is generally divided into multiple files and folders, with each part responsible for a particular task. Components handle the user interface, stylesheets define appearance, services manage API communication, and test files verify application behaviour.

React does not enforce one specific folder structure. Developers can organize files according to project size, team preferences, and application requirements. For beginner projects, a simple structure is sufficient. For larger applications, feature-based organization can make the codebase easier to maintain.

Why Is Project Structure Important?

  • Readability: Developers can quickly understand where code belongs.
  • Reusability: Common components can be shared across multiple pages.
  • Maintainability: Changes can be made without unnecessarily affecting unrelated features.
  • Scalability: New pages and features can be added systematically.
  • Collaboration: Team members can work on separate features more efficiently.
  • Testing: Components and their tests can be organized together.
  • Debugging: Errors can be traced to the relevant component, service, or module.

2. Creating a React Project

Vite is a popular build tool for creating React applications. It provides a development server and build process for modern frontend projects.

Step 1: Create a React Project

npm create vite@latest my-react-app -- --template react

Step 2: Navigate to the Project Folder

cd my-react-app

Step 3: Install Dependencies

npm install

Step 4: Start the Development Server

npm run dev

After running the command, open the local URL displayed in the terminal. The default Vite development server commonly uses port 5173 when that port is available.

3. Basic React Project Folder Structure

A newly created React project using Vite commonly contains the following files and folders. Exact filenames can vary depending on the template selected.

my-react-app/
├── node_modules/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   │   └── react.svg
│   ├── App.jsx
│   ├── App.css
│   ├── index.css
│   └── main.jsx
├── .gitignore
├── index.html
├── package.json
├── package-lock.json
└── vite.config.js

This is a starting structure rather than a mandatory structure for every React application. As the project grows, you can create folders for components, pages, hooks, services, routes, tests, and other shared resources.

4. Understanding Important Folders and Files

4.1 node_modules Folder

The node_modules folder contains packages installed through npm or another package manager. These packages provide the libraries and tools required by the application.

Examples include React, React DOM, Vite, testing libraries, and routing libraries.

  • It is generated and managed by the package manager.
  • Developers generally should not edit its contents manually.
  • It is normally excluded from version control using .gitignore.
  • Dependencies can be restored by running npm install.

4.2 public Folder

The public folder stores static assets that need to be served directly without being imported into the JavaScript module graph.

Examples include:

  • Favicon files.
  • Robots.txt.
  • Static images referenced by URL.
  • Other public files that should retain their filenames.

Example:

public/
├── favicon.ico
├── robots.txt
└── images/
    └── company-logo.png

In a Vite application, a file stored at public/images/company-logo.png can generally be referenced using /images/company-logo.png.

function CompanyLogo() {
  return (
    <img
      src="/images/company-logo.png"
      alt="Company logo"
    />
  );
}

export default CompanyLogo;

4.3 src Folder

The src folder contains most of the application's source code. It is where developers usually place React components, application logic, stylesheets, hooks, route definitions, and API services.

Example expanded structure:

src/
├── assets/
├── components/
├── pages/
├── layouts/
├── hooks/
├── services/
├── routes/
├── context/
├── utils/
├── styles/
├── App.jsx
├── App.css
├── index.css
└── main.jsx

These folders are optional conventions. Add them when they make the project clearer instead of creating unnecessary folders for a small application.

4.4 main.jsx File

The main.jsx file is commonly the entry point of a Vite React application. It imports React, creates the root, and renders the main application component into the HTML document.

// src/main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import './index.css';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Important responsibilities of main.jsx include:

  • Importing the root application component.
  • Mounting React into the DOM element with the ID root.
  • Importing global CSS.
  • Wrapping the application with providers when required, such as a router or context provider.

4.5 App.jsx File

The App.jsx file commonly contains the root application component. In a small application, it may display the main interface. In a larger application, it may organize shared layouts and routes.

// src/App.jsx
import './App.css';

function App() {
  return (
    <main className="app">
      <h1>Welcome to React</h1>
      <p>This is my first React application.</p>
    </main>
  );
}

export default App;

4.6 App.css File

The App.css file commonly contains styles associated with the root application component or its main layout.

/* src/App.css */
.app {
  max-width: 1000px;
  margin: 0 auto;
  padding: 24px;
}

.app h1 {
  font-size: 2rem;
  color: #243b53;
}

4.7 index.css File

The index.css file commonly contains global styles applied throughout the application, including default font settings, body styles, and box-sizing rules.

/* src/index.css */
* {
  box-sizing: border-box;
}

body {
  margin: 0;
  font-family: Arial, sans-serif;
  background: #f5f7fa;
  color: #222;
}

button,
input,
textarea,
select {
  font: inherit;
}

4.8 index.html File

The index.html file is the HTML entry point for a Vite application. It contains the root DOM element where React mounts and a module script that loads the JavaScript entry point.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

The element with id="root" must match the element selected in main.jsx.

4.9 package.json File

The package.json file describes the project, its scripts, and its dependencies.

{
  "name": "my-react-app",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "YOUR_INSTALLED_VERSION",
    "react-dom": "YOUR_INSTALLED_VERSION"
  },
  "devDependencies": {
    "vite": "YOUR_INSTALLED_VERSION"
  }
}

The version placeholders above are explanatory. A real project should retain the valid versions generated by its package manager rather than copying these placeholders literally.

Common commands include:

  • npm run dev — starts the development server.
  • npm run build — builds the application for production.
  • npm run preview — previews the production build locally.

4.10 vite.config.js File

The vite.config.js file stores configuration for Vite, such as plugins, aliases, development server settings, and test settings when configured.

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()]
});

4.11 .gitignore File

The .gitignore file specifies generated files and local files that Git should normally not track.

node_modules/
dist/
.env.local
.env.*.local

Environment files containing secrets must never be committed. In frontend applications, environment variables exposed to client-side code should not contain private server credentials because bundled client code can be inspected by users.

5. Organizing Components in React

Components are reusable building blocks of a React user interface. A component may represent a button, navigation bar, card, form, modal, sidebar, or complete page.

React components can be grouped in a dedicated components folder.

src/
├── components/
│   ├── Navbar.jsx
│   ├── Footer.jsx
│   ├── Button.jsx
│   └── ProductCard.jsx
├── App.jsx
└── main.jsx

Example: Button Component

// src/components/Button.jsx
function Button({ children, onClick, type = 'button' }) {
  return (
    <button type={type} onClick={onClick}>
      {children}
    </button>
  );
}

export default Button;

Using the Reusable Button

// src/App.jsx
import Button from './components/Button.jsx';

function App() {
  return (
    <div>
      <h1>Reusable Components</h1>
      <Button onClick={() => alert('Button clicked!')}>
        Click Me
      </Button>
    </div>
  );
}

export default App;

The button can be reused in different parts of the application by passing different children and event handlers through props.

6. Organizing Pages

The pages folder is commonly used for components that represent complete screens or route-level views. This convention is especially useful in applications with multiple pages.

src/
├── pages/
│   ├── Home.jsx
│   ├── About.jsx
│   ├── Contact.jsx
│   └── NotFound.jsx
├── components/
└── App.jsx

Example: Home Page

// src/pages/Home.jsx
function Home() {
  return (
    <section>
      <h1>Home Page</h1>
      <p>Welcome to our website.</p>
    </section>
  );
}

export default Home;

Example: About Page

// src/pages/About.jsx
function About() {
  return (
    <section>
      <h1>About Us</h1>
      <p>Learn more about our company.</p>
    </section>
  );
}

export default About;

Separating pages from shared components makes it easier to locate the code for a specific screen and reuse common interface elements.

7. Organizing Layouts

Layouts define the shared visual structure around pages. Examples include a dashboard layout, an authenticated application layout, and a public website layout.

src/
├── layouts/
│   ├── MainLayout.jsx
│   └── DashboardLayout.jsx
├── pages/
└── components/

Example: Main Layout

// src/layouts/MainLayout.jsx
import Navbar from '../components/Navbar.jsx';
import Footer from '../components/Footer.jsx';

function MainLayout({ children }) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
      <Footer />
    </>
  );
}

export default MainLayout;

A layout allows multiple pages to share the same navigation and footer without repeating that markup in every page component.

8. Organizing Routes

Routing determines which page or component is displayed for a given URL. A routing library such as React Router is often used when a React application needs multiple client-side routes.

Install React Router if your project requires it:

npm install react-router-dom

Example structure:

src/
├── routes/
│   └── AppRoutes.jsx
├── pages/
│   ├── Home.jsx
│   ├── About.jsx
│   └── NotFound.jsx
├── components/
└── App.jsx

Example: Route Configuration

// src/routes/AppRoutes.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from '../pages/Home.jsx';
import About from '../pages/About.jsx';
import NotFound from '../pages/NotFound.jsx';

function AppRoutes() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

export default AppRoutes;

Render the route configuration from App.jsx:

// src/App.jsx
import AppRoutes from './routes/AppRoutes.jsx';

function App() {
  return <AppRoutes />;
}

export default App;

9. Organizing API Services

API service files contain functions responsible for communicating with external services or backend endpoints. Separating API calls from UI components helps make the code easier to test, reuse, and maintain.

src/
├── services/
│   ├── api.js
│   └── userService.js
├── pages/
└── components/

Example: User Service

// src/services/userService.js
export async function getUsers() {
  const response = await fetch('/api/users');

  if (!response.ok) {
    throw new Error('Unable to fetch users');
  }

  return response.json();
}

Using the Service in a Component

// src/pages/Users.jsx
import { useEffect, useState } from 'react';
import { getUsers } from '../services/userService.js';

function Users() {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState('');

  useEffect(() => {
    let active = true;

    getUsers()
      .then((data) => {
        if (active) setUsers(data);
      })
      .catch(() => {
        if (active) setError('Unable to load users');
      });

    return () => {
      active = false;
    };
  }, []);

  if (error) return <p role="alert">{error}</p>;

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default Users;

This example demonstrates service separation and a basic guard against updating state after the effect is cleaned up. For more complex requests, use request cancellation, such as an AbortController, where appropriate. Also add explicit loading and empty states when required by the interface.

10. Organizing Custom Hooks

Custom hooks allow developers to reuse stateful React logic across components. They are usually named with the use prefix, such as useAuth, useFetch, or useWindowSize.

src/
├── hooks/
│   ├── useAuth.js
│   └── useWindowSize.js
└── App.jsx

Example: useWindowSize Hook

// src/hooks/useWindowSize.js
import { useEffect, useState } from 'react';

export function useWindowSize() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    function updateWidth() {
      setWidth(window.innerWidth);
    }

    window.addEventListener('resize', updateWidth);

    return () => {
      window.removeEventListener('resize', updateWidth);
    };
  }, []);

  return width;
}

Using the Custom Hook

import { useWindowSize } from './hooks/useWindowSize.js';

function WindowInfo() {
  const width = useWindowSize();

  return <p>Window width: {width}px</p>;
}

export default WindowInfo;

When using hooks in server-rendered environments, make sure browser-only APIs such as window are accessed safely. A client-only Vite application can use the example directly in a browser environment.

11. Organizing Context and Global State

Context is useful for sharing data across multiple components without passing props through every intermediate component. Common examples include authentication details, theme preferences, or locale settings.

src/
├── context/
│   ├── AuthContext.jsx
│   └── ThemeContext.jsx
├── components/
└── App.jsx

For larger applications, state may be organized with a dedicated state-management solution. Use local component state when the data is only needed by one component or a small group of related components. Introduce global state when it genuinely improves sharing and consistency.

12. Organizing Utility Functions

The utils folder commonly contains small reusable helper functions that are not specific to a single UI component.

src/
├── utils/
│   ├── formatDate.js
│   ├── formatCurrency.js
│   └── validateEmail.js

Example: Currency Formatter

// src/utils/formatCurrency.js
export function formatCurrency(amount) {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR'
  }).format(amount);
}

Using the Utility

import { formatCurrency } from './utils/formatCurrency.js';

function Price() {
  return <p>{formatCurrency(1499)}</p>;
}

export default Price;

Utility functions should generally be small, focused, and easy to test independently.

13. Organizing Assets and Styles

The assets folder commonly stores files that are imported into application modules, while the styles folder can contain shared stylesheets, design tokens, or theme definitions.

src/
├── assets/
│   ├── images/
│   ├── icons/
│   └── fonts/
├── styles/
│   ├── variables.css
│   └── responsive.css
└── components/

Assets imported from src can be processed by the build tool. Static files in public are served directly, so choose the location based on how each asset needs to be referenced.

14. Organizing Tests

Tests verify that components and application logic behave as expected. Tests can be placed beside the component they test or in a separate test directory.

Co-located Test Structure

src/
├── components/
│   ├── Button.jsx
│   └── Button.test.jsx
├── pages/
│   ├── Home.jsx
│   └── Home.test.jsx
└── utils/
    ├── formatCurrency.js
    └── formatCurrency.test.js

Co-located tests make it easier to locate the relevant test when editing a component. Larger projects may also use a dedicated tests folder.

15. Feature-Based Project Structure

For a larger application, a feature-based structure groups related code by business functionality rather than separating every file by type. This approach is useful when different features have their own components, hooks, services, and tests.

src/
├── features/
│   ├── auth/
│   │   ├── components/
│   │   ├── hooks/
│   │   ├── services/
│   │   └── pages/
│   ├── products/
│   │   ├── components/
│   │   ├── hooks/
│   │   ├── services/
│   │   └── pages/
│   └── cart/
│       ├── components/
│       ├── hooks/
│       ├── services/
│       └── pages/
├── shared/
│   ├── components/
│   ├── hooks/
│   └── utils/
├── App.jsx
└── main.jsx

Benefits of Feature-Based Organization

  • Related code is kept close together.
  • Developers can locate feature-specific logic more easily.
  • Shared components remain separate from feature-specific components.
  • Teams can work on separate features with clearer boundaries.
  • Features can be modified with less need to search unrelated folders.

There is no single correct structure for every React application. A small project may work best with a few simple folders, while a large application may benefit from feature-based organization.

16. Component-Based vs Feature-Based Structure

Component-Based Structure Feature-Based Structure
Groups files by type, such as components and hooks. Groups files by application feature.
Simple to understand in small applications. Useful when applications have multiple substantial features.
Shared UI components are easy to locate. Feature-specific UI and logic are kept close together.
Related files may be spread across folders as the app grows. Developers can often work within one feature folder.
Example: components/, hooks/, pages/. Example: features/auth/, features/products/.

17. Complete Example: React E-Commerce Project Structure

An e-commerce application may include authentication, product listings, a shopping cart, checkout, and order history. Each feature can have its own components and services, while common UI elements live in a shared folder.

ecommerce-app/
├── public/
│   └── favicon.ico
├── src/
│   ├── assets/
│   │   └── images/
│   ├── components/
│   │   ├── Navbar.jsx
│   │   ├── Footer.jsx
│   │   ├── Button.jsx
│   │   └── LoadingSpinner.jsx
│   ├── layouts/
│   │   └── MainLayout.jsx
│   ├── routes/
│   │   └── AppRoutes.jsx
│   ├── features/
│   │   ├── auth/
│   │   │   ├── LoginPage.jsx
│   │   │   └── authService.js
│   │   ├── products/
│   │   │   ├── ProductList.jsx
│   │   │   ├── ProductCard.jsx
│   │   │   └── productService.js
│   │   ├── cart/
│   │   │   ├── CartPage.jsx
│   │   │   └── cartUtils.js
│   │   └── orders/
│   │       └── OrderHistory.jsx
│   ├── hooks/
│   │   └── useAuth.js
│   ├── services/
│   │   └── apiClient.js
│   ├── utils/
│   │   └── formatCurrency.js
│   ├── styles/
│   │   └── responsive.css
│   ├── App.jsx
│   ├── App.css
│   ├── index.css
│   └── main.jsx
├── .gitignore
├── index.html
├── package.json
└── vite.config.js

This is an illustrative structure. A real project should include only the folders and files it needs. For example, if the application has no authentication feature, an auth folder is unnecessary.

18. Naming Conventions in React Projects

Consistent naming conventions make a project easier to understand and reduce confusion when searching for files.

Item Common Convention Example
React component PascalCase ProductCard.jsx
Page component PascalCase HomePage.jsx
Custom hook camelCase with use prefix useAuth.js
Utility function camelCase formatCurrency.js
CSS file Often matches component name ProductCard.css
Test file Component or module name plus test suffix ProductCard.test.jsx
Constants Often uppercase for fixed values API_BASE_URL

These are common conventions, not mandatory rules. Follow the naming style already established in the project.

19. Best Practices for React Project Structure

  • Keep components small and focused on a clear responsibility.
  • Use reusable components for repeated UI patterns.
  • Keep API communication separate from presentation where appropriate.
  • Use custom hooks to reuse stateful logic.
  • Separate route-level pages from shared interface components.
  • Use feature-based folders when the application becomes large enough to benefit from them.
  • Avoid creating too many folders before they are needed.
  • Use clear, consistent file and folder names.
  • Keep global styles separate from component-specific styles.
  • Store static assets in a suitable location.
  • Place tests near the code they cover or use a consistent dedicated test folder.
  • Keep private credentials on the server rather than exposing them in frontend code.
  • Use environment variables appropriately for environment-specific configuration.
  • Remove unused files, imports, and dependencies.
  • Use Git and a suitable .gitignore file to manage source code.
  • Choose a structure that suits the project's size and team rather than following a folder template blindly.

20. Common Mistakes to Avoid

Mistake Better Practice
Putting the entire application into one large component. Split the interface into focused, reusable components.
Mixing unrelated features in the same folder. Organize related files by component type or feature.
Repeating the same navbar or footer on every page. Create shared components or a layout component.
Writing API request logic repeatedly in multiple components. Extract reusable service functions where appropriate.
Creating unnecessary folders for a tiny application. Start simple and expand the structure as the project grows.
Using unclear file names such as file1.jsx. Choose descriptive names that explain the file's purpose.
Committing node_modules to Git. Exclude generated dependency folders from version control.
Storing private API keys in client-side code. Keep secrets on the server and expose only appropriate public configuration.
Putting all application logic into App.jsx. Move reusable logic into suitable components, hooks, services, or modules.

21. Interview Questions and Answers

Q1. What is React project structure?

React project structure is the organization of source files, components, styles, assets, services, routes, and tests in a React application.

Q2. Does React enforce a specific folder structure?

No. React allows developers to organize files according to their needs. Common approaches include organizing by file type, route, or feature.

Q3. What is the purpose of the src folder?

The src folder commonly contains the application's source code, including components, stylesheets, hooks, services, and route definitions.

Q4. What is the purpose of main.jsx?

In a typical Vite React project, main.jsx is the entry point that mounts the root React component into the HTML document.

Q5. What is the difference between App.jsx and main.jsx?

main.jsx initializes and mounts the application. App.jsx commonly defines the root component and organizes the main UI or routes.

Q6. What is the purpose of the public folder?

It contains static files that should be served directly, such as favicons and files referenced through public URLs.

Q7. Why do we create a components folder?

It provides a consistent place for reusable interface elements such as buttons, cards, navigation bars, and modals.

Q8. What is the purpose of a pages folder?

A pages folder commonly contains complete screen components associated with application routes.

Q9. What is feature-based project organization?

It groups related components, hooks, services, and tests according to business features, such as authentication, products, or orders.

Q10. What is the purpose of a services folder?

It commonly contains modules that communicate with APIs or external systems, keeping that logic separate from the UI where appropriate.

Q11. What is the purpose of a hooks folder?

It provides a location for reusable custom hooks that share stateful or lifecycle-related logic between components.

Q12. Why is project structure important in large applications?

A clear structure improves maintainability, reusability, collaboration, testing, debugging, and the ability to add new features.

Q13. What is the purpose of package.json?

It records project metadata, scripts, and dependencies needed to develop, test, and build the application.

Q14. Where should component tests be stored?

They can be placed next to the component or in a dedicated test directory. Consistency is more important than choosing one universal location.

Q15. What is the difference between component-based and feature-based organization?

Component-based organization groups files by type, while feature-based organization groups related code by application functionality.

22. Practical Exercises

  1. Create a React project using Vite and inspect its default folders.
  2. Create a components folder and build a reusable button.
  3. Create a pages folder with Home and About pages.
  4. Create a shared Navbar component and use it on multiple pages.
  5. Install React Router and configure the required routes.
  6. Create a services folder and move API request logic into a service module.
  7. Create a custom hook that can be reused by more than one component.
  8. Write tests for a component and its user interactions.
  9. Refactor a large component into smaller, focused components.
  10. Organize a sample e-commerce application using feature-based folders.

23. Revision Checklist

  • Understand the purpose of the React project structure.
  • Know how to create and run a React project using Vite.
  • Understand src, public, main.jsx, and App.jsx.
  • Understand the roles of index.html, package.json, and vite.config.js.
  • Know how to organize reusable components and pages.
  • Understand layouts and routing.
  • Know where API services, hooks, utilities, and tests can be stored.
  • Understand component-based and feature-based organization.
  • Follow consistent naming conventions.
  • Keep the structure simple for small applications and scalable for larger ones.
  • Protect private credentials and avoid committing generated files.

24. Official Learning Resources

25. Conclusion

React project structure is an important foundation for building organized, maintainable, and scalable applications. Understanding the roles of the src folder, components, pages, layouts, routes, hooks, services, utilities, assets, and tests helps developers keep code clean and reusable.

For smaller applications, a simple folder structure is often enough. As the project grows, organizing code by features can improve maintainability and collaboration. The best structure is one that makes the application easy to understand, test, and extend.

To learn more about React development, visit the JustAcademy React JS Training Course or Register for React JS Course Demo.

Previous Next
whatsapp