| How to Manage Environment Variables in React :👈 | 👉:How to Test React Components with React Testing Library |
Common React Architecture Mistakes |
Common React Architecture Mistakes
1. What Is React Architecture?
React architecture refers to how we organize components, state, business logic, API calls, routing, and shared functionality within a React application.
A good architecture provides:
- Clear separation of responsibilities.
- Reusable and maintainable components.
- Predictable state management.
- Organized API communication.
- Easy testing and debugging.
- Flexibility as the application grows.
React does not enforce one particular architecture. Developers need to choose an organization that suits the application's requirements.
2. Common React Architecture Mistakes
1. Putting Everything Inside One Component
Mistake: Creating a large component that handles API calls, state management, validation, business logic, and UI rendering.
Bad example:
function ProductsPage() {
const [products, setProducts] = useState([]);
const [search, setSearch] = useState("");
const [loading, setLoading] = useState(false);
// API calls
// Search logic
// Filtering logic
// Form validation
// Cart operations
// Large JSX
}
Why is this a problem?
- The component becomes difficult to understand.
- Changes can affect unrelated functionality.
- Testing becomes harder.
- Code reuse becomes difficult.
Better approach: Separate responsibilities into components, custom Hooks, utilities, and services.
2. Mixing UI and Business Logic
Mistake: Writing all business rules directly inside JSX or UI components.
Bad example:
function OrderSummary({ order }) {
return (
<div>
{order.items.reduce((total, item) => {
return total + item.price * item.quantity;
}, 0) > 1000
? "Eligible for discount"
: "No discount"}
</div>
);
}
When business rules become complex, keeping them inside UI components makes the code harder to maintain and test.
Better approach: Move reusable business rules into separate functions.
export function calculateOrderTotal(items) {
return items.reduce(
(total, item) => total + item.price * item.quantity,
0
);
}
export function isEligibleForDiscount(total) {
return total > 1000;
}
Use these functions inside the component:
function OrderSummary({ order }) {
const total = calculateOrderTotal(order.items);
return (
<div>
{isEligibleForDiscount(total)
? "Eligible for discount"
: "No discount"}
</div>
);
}
3. Poor Folder Structure
Mistake: Keeping all components, services, Hooks, and utilities in a few large folders without clear organization.
Example of a poorly organized structure:
src/
components/
files/
helpers/
services/
common/
As the application grows, developers may struggle to locate related functionality.
Better approach: Use feature-based or hybrid organization.
src/
app/
App.jsx
routes.jsx
features/
products/
components/
ProductCard.jsx
ProductList.jsx
hooks/
useProducts.js
services/
productService.js
pages/
ProductsPage.jsx
orders/
components/
hooks/
services/
pages/
users/
components/
hooks/
services/
pages/
shared/
components/
hooks/
utils/
config/
env.js
Important: Do not create unnecessary folders for every small component. The goal is clear responsibility, not maximum folder count.
4. Using Global State for Everything
Mistake: Storing every piece of state in Redux, Zustand, or Context API.
For example, a search input value used by only one component does not necessarily need global state.
Why is this a problem?
- Introduces unnecessary complexity.
- Makes state ownership unclear.
- Can create unnecessary dependencies between components.
- Increases maintenance overhead.
Better approach: Choose state management based on the scope and lifetime of the data.
| State Type | Recommended Approach |
|---|---|
| Input field value | useState |
| Complex local form state | useReducer or a form library |
| Shared application preferences | Context or a state library |
| Authentication state | Context or a state library, with secure server-side authentication design |
| API server data | TanStack Query or another server-state solution |
| URL filters and pagination | URL search parameters |
5. Confusing Client State with Server State
Mistake: Managing API data and local UI state in exactly the same way.
These are different types of state.
- Client state: Search text, modal visibility, selected tab, theme.
- Server state: Products, orders, users, API responses.
Server state requires additional considerations such as:
- Loading and error states.
- Request caching.
- Background refetching.
- Cache invalidation.
- Request synchronization.
Better approach: Use local React state for UI state and a server-state library such as TanStack Query when the application benefits from caching and request lifecycle management.
import { useQuery } from "@tanstack/react-query";
function ProductsPage() {
const { data, isLoading, error } = useQuery({
queryKey: ["products"],
queryFn: getProducts
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Unable to load products</p>;
return <ProductList products={data} />;
}
6. Making API Calls Directly in Every Component
Mistake: Repeating fetch or Axios logic in multiple components.
Bad example:
function ProductsPage() {
useEffect(() => {
fetch("/api/products")
.then(response => response.json())
.then(data => setProducts(data));
}, []);
}
If every component implements its own API communication, common concerns such as error handling, authentication headers, and response processing become duplicated.
Better approach: Create a centralized API client and feature-specific service modules.
// services/apiClient.js
const API_BASE_URL = "/api";
export async function apiGet(endpoint) {
const response = await fetch(`${API_BASE_URL}${endpoint}`);
if (!response.ok) {
throw new Error("API request failed");
}
return response.json();
}
// features/products/services/productService.js
import { apiGet } from "../../../../services/apiClient";
export function getProducts() {
return apiGet("/products");
}
Components can now use the service rather than implementing the HTTP communication themselves.
7. Creating Too Many Reusable Components
Mistake: Turning every small JSX section into a separate component, even when there is no meaningful reuse or independent responsibility.
For example, creating separate components for every individual label, wrapper, and simple text element can make navigation through the codebase unnecessarily difficult.
Better approach: Extract a component when it:
- Has a clear responsibility.
- Is reused in multiple places.
- Contains meaningful UI complexity.
- Needs independent testing or state management.
- Makes the parent component easier to understand.
Reusability is valuable, but not every JSX element needs its own component.
8. Passing Too Many Props Through Multiple Components
Mistake: Passing data through components that do not use it, simply to reach a deeply nested child.
Example:
<App user={user}>
<Dashboard user={user}>
<ProfileSection user={user}>
<UserDetails user={user} />
</ProfileSection>
</Dashboard>
</App>
This is known as prop drilling.
Better approach: Depending on the situation, use:
- Component composition.
- Context API.
- A state management library.
However, passing props is not a bad practice. It is often the simplest and clearest solution when data is needed by nearby components.
9. Creating Custom Hooks Without a Real Need
Mistake: Creating custom Hooks for simple expressions or one-line operations that do not need reusable stateful logic.
Unnecessary abstraction:
function useFullName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
This function does not use React Hooks or manage state. A normal utility function is more appropriate.
Better approach:
function getFullName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
Use custom Hooks when sharing stateful behavior or React-specific logic, such as fetching data, tracking window size, or managing subscriptions.
10. Incorrect useEffect Usage
Mistake: Using useEffect for calculations that can be performed directly during rendering, or creating effects with incorrect dependencies.
Unnecessary example:
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(price * quantity);
}, [price, quantity]);
The total can be calculated directly from existing state and props.
Better approach:
const total = price * quantity;
Use useEffect primarily to synchronize React with external systems, such as network connections, browser APIs, subscriptions, and third-party libraries.
11. Not Handling Loading, Error, and Empty States
Mistake: Displaying only successful API results without considering other possible states.
A real application should handle:
- Loading: Data is being retrieved.
- Error: The request failed.
- Empty: The request succeeded, but no records were found.
- Success: Data is available.
Better approach:
if (isLoading) {
return <p>Loading products...</p>;
}
if (error) {
return <p>Something went wrong.</p>;
}
if (products.length === 0) {
return <p>No products found.</p>;
}
return <ProductList products={products} />;
12. Ignoring Error Boundaries
Mistake: Allowing an error in one part of the component tree to disrupt the entire application interface.
Better approach: Use Error Boundaries at appropriate application, route, or feature boundaries.
They help display fallback UI when descendant components encounter rendering errors. They do not automatically handle every asynchronous error or event-handler exception.
13. Overusing Context API
Mistake: Putting unrelated application data into one large Context provider.
For example, combining authentication, theme, shopping cart, notifications, and product data in one provider can make state management harder.
When a Context value changes, its consumers may render again.
Better approach:
- Separate unrelated Context responsibilities.
- Keep local state local.
- Memoize provider values when appropriate.
- Use a dedicated state management solution when requirements justify it.
14. Premature Optimization
Mistake: Adding useMemo, useCallback, React.memo, virtualization, and complex caching before identifying an actual performance problem.
These techniques can introduce additional code and maintenance costs.
Better approach:
- Build a clear and correct implementation first.
- Measure performance using React DevTools Profiler and browser tools.
- Identify the actual bottleneck.
- Apply an appropriate optimization.
- Measure again to verify the improvement.
15. Not Using Lazy Loading for Large Applications
Mistake: Loading every route and large feature module immediately, even when users do not need them.
Better approach: Use route-level code splitting with React.lazy and Suspense.
import { lazy, Suspense } from "react";
const ProductsPage = lazy(
() => import("./features/products/ProductsPage")
);
function App() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<ProductsPage />
</Suspense>
);
}
This allows the application to load the relevant code when needed.
16. Poor Separation of Feature Responsibilities
Mistake: Organizing the entire application only by technical file type, even when features have many related files.
For example:
components/
ProductCard.jsx
OrderCard.jsx
UserCard.jsx
services/
productService.js
orderService.js
userService.js
hooks/
useProducts.js
useOrders.js
useUsers.js
This can become difficult to navigate in a large application because related feature files are spread across multiple folders.
Better approach: Keep feature-specific files together.
features/
products/
components/
hooks/
services/
orders/
components/
hooks/
services/
users/
components/
hooks/
services/
17. Not Defining Clear Component Responsibilities
Mistake: Allowing components to depend on too many unrelated application details.
For example, a reusable ProductCard should not need to know how the application authenticates users, loads products, or manages API caching.
Better approach: Give components clear responsibilities and pass the data and callbacks they need.
function ProductCard({ product, onAddToCart }) {
return (
<div>
<h3>{product.name}</h3>
<p>{product.price}</p>
<button onClick={() => onAddToCart(product)}>
Add to Cart
</button>
</div>
);
}
18. Not Managing Routes Properly
Mistake: Keeping all page-selection logic inside one large component with multiple conditional statements.
Better approach: Use a routing library such as React Router to define routes and organize page navigation.
const routes = [
{ path: "/", element: <HomePage /> },
{ path: "/products", element: <ProductsPage /> },
{ path: "/orders", element: <OrdersPage /> }
];
In a real application, connect route definitions to the router configuration and use appropriate route protection where required.
19. Ignoring Testing and Maintainability
Mistake: Writing tightly coupled components and business logic that are difficult to test independently.
Better approach:
- Test important business rules independently.
- Test components based on user-visible behavior.
- Test API service behavior and error handling.
- Use integration tests for important workflows.
- Keep components and services loosely coupled.
20. Overengineering the Application
Mistake: Introducing unnecessary design patterns, multiple state libraries, excessive abstraction layers, and complex folder structures before the requirements justify them.
Why is this a problem?
- Increases development time.
- Makes onboarding difficult.
- Creates unnecessary maintenance work.
- Can make simple changes complicated.
Better approach: Follow YAGNI (You Aren't Gonna Need It). Start with the simplest architecture that meets current requirements and evolve it when real needs arise.
3. Recommended React Architecture
The following is an example of a feature-based architecture for a medium-to-large React application.
src/
│
├── app/
│ ├── App.jsx
│ ├── routes.jsx
│ └── providers.jsx
│
├── features/
│ ├── products/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ ├── utils/
│ │ └── pages/
│ │
│ ├── orders/
│ │ ├── components/
│ │ ├── hooks/
│ │ ├── services/
│ │ └── pages/
│ │
│ └── users/
│ ├── components/
│ ├── hooks/
│ ├── services/
│ └── pages/
│
├── shared/
│ ├── components/
│ ├── hooks/
│ └── utils/
│
├── services/
│ └── apiClient.js
│
├── config/
│ └── env.js
│
└── main.jsx
Responsibility of Each Layer
| Layer | Responsibility |
|---|---|
| App | Application initialization, providers, and routing. |
| Features | Feature-specific components, Hooks, services, and pages. |
| Components | Rendering UI and handling user interactions. |
| Hooks | Reusable React stateful logic. |
| Services | API communication and external service integration. |
| Utils | Reusable functions and business calculations. |
| Shared | Common functionality used by multiple features. |
| Config | Application configuration and environment settings. |
4. Example: Good vs Bad Architecture
Consider an e-commerce application with products, orders, users, and shopping cart functionality.
| Bad Architecture | Better Architecture |
|---|---|
| One large component handles everything. | Separate components based on responsibilities. |
| API calls repeated across components. | Centralized API client and feature services. |
| All state stored globally. | State managed according to its scope and purpose. |
| Business logic mixed with JSX. | Business rules separated into utilities or domain-specific modules. |
| All files organized by technical type. | Feature-based or hybrid folder structure. |
| Unnecessary abstractions. | Simple solutions that match actual requirements. |
| No error or loading handling. | Consistent handling of application states. |
5. How to Decide Whether an Architecture Change Is Needed
Before introducing a new pattern, library, or abstraction, consider these questions:
- Does the current implementation have a real maintenance problem?
- Is the same logic repeated in multiple places?
- Are components handling unrelated responsibilities?
- Is state shared across multiple independent features?
- Is API caching or synchronization becoming difficult?
- Will the proposed solution reduce complexity rather than increase it?
- Can the team understand and maintain the new design?
If the current design works well and is easy to maintain, there may be no reason to change it.
6. Interview Questions and Answers
Q1. What are common React architecture mistakes?
Common mistakes include large components, mixing UI and business logic, poor folder organization, unnecessary global state, duplicated API calls, excessive Context usage, and overengineering.
Q2. What is feature-based architecture?
Feature-based architecture organizes related files around business features such as products, orders, and users rather than separating the entire application only by technical file type.
Q3. Should all React state be managed by Redux?
No. Local UI state should generally remain in components. Global state libraries should be used when multiple independent parts of the application need shared state.
Q4. What is the difference between client state and server state?
Client state is managed by the frontend, such as selected tabs and modal visibility. Server state represents data retrieved from external systems, such as products and orders.
Q5. Why should API calls be separated from components?
Separating API communication improves reuse, maintainability, testability, and consistency in error handling.
Q6. When should you create a custom Hook?
Create a custom Hook when you need to reuse React-specific stateful logic or synchronize with external systems across components.
Q7. Is Context API a replacement for Redux?
Not necessarily. Context is primarily a mechanism for sharing values across a component tree. Redux provides a more comprehensive state management approach with additional tooling and predictable update patterns.
Q8. How do you avoid overengineering React applications?
Start with simple solutions, introduce abstractions only when they provide clear value, avoid unnecessary dependencies, and optimize based on measured problems.
Q9. How do you improve React application maintainability?
Use clear component responsibilities, feature-based organization, centralized API services, appropriate state management, reusable business logic, and meaningful automated tests.
Q10. Does a good folder structure automatically make an application scalable?
No. Folder structure helps organize code, but scalability also depends on clear responsibilities, manageable dependencies, appropriate state management, testing, and good engineering practices.
7. Final Best Practices
- Keep components focused on clear responsibilities.
- Separate UI, business logic, and API communication where useful.
- Organize code around features as the application grows.
- Keep local state local whenever possible.
- Choose client-state and server-state solutions appropriately.
- Avoid unnecessary abstractions and dependencies.
- Use Error Boundaries and handle loading, error, and empty states.
- Apply performance optimization only when there is a measurable need.
- Write tests for important application behavior.
- Keep architecture simple enough for the development team to understand.
Conclusion
The biggest React architecture mistake is making the application more complicated than its actual requirements.
A good React architecture is not about using every design pattern or state management library. It is about organizing responsibilities clearly, managing dependencies carefully, and making future changes easier without unnecessary complexity.
| How to Manage Environment Variables in React :👈 | 👉:How to Test React Components with React Testing Library |
Comments and Discussion