Beyond Components: Building Maintainable API-Driven React Applications with TypeScript
React makes it easy to build user interfaces using reusable components. However, as an application grows, managing API responses, business logic, data transformations and component responsibilities becomes increasingly challenging.
A common pattern in smaller React applications is to fetch data directly inside components, transform the response and manage everything using local state.
This works initially, but as the application grows, the same responsibilities often become scattered across multiple components.
The result?
- API integration becomes difficult to maintain.
- Components become tightly coupled to backend response structures.
- Business logic gets duplicated.
- Changes to API contracts affect multiple parts of the application.
- Testing individual responsibilities becomes harder.
In this article, we'll explore a practical approach to structuring API-driven React applications using TypeScript, DTOs, mapping functions, repositories and use cases.
The objective is not to introduce unnecessary abstractions. It is to create clear boundaries between the UI, application logic and external data sources.
1. Understanding the Problem with Component-Centric API Integration
Consider a typical React component that fetches product information.
const ProductList = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch("/api/products")
.then((response) => response.json())
.then((data) => setProducts(data.result));
}, []);
return (
<div>
{products.map((product) => (
<div key={product.id}>
{product.productName}
</div>
))}
</div>
);
};
There is nothing inherently wrong with this implementation for a small application.
However, imagine the application now has:
- Product listing and product details.
- Multiple API endpoints.
- Pagination and filtering.
- Different backend response structures.
- Data transformations.
- Reusable business rules.
The component gradually becomes responsible for more than rendering the UI.
A better approach is to separate these responsibilities.
2. Introducing a Layered Frontend Architecture
One practical way to organize an API-driven React application is to introduce separate layers.
For this example, we'll use:
- Presentation Layer
- Application Layer
- Domain Layer
- Data Layer
Each layer has a specific responsibility.
Presentation Layer
Responsible for rendering the UI and handling user interactions.
Examples:
- React components
- Custom hooks
- Pages
- UI state
The presentation layer should not need to understand the backend's raw response structure.
Application Layer
Responsible for coordinating application operations.
Examples:
- Get all products
- Get product details
- Create a product
- Update a product
This is where use cases can be introduced.
Domain Layer
Contains application-specific business models and rules.
For example, a Product entity should represent the product information required by the application rather than simply copying the backend response.
Data Layer
Responsible for communicating with external data sources.
Examples:
- API services
- Repository implementations
- DTOs
- Data mappers
This separation makes it easier to modify API integration without unnecessarily changing the UI.
3. DTOs: Separating API Contracts from Application Models
One important concept in API-driven applications is the Data Transfer Object (DTO).
A DTO represents the structure of data received from or sent to an external system.
For example, an API might return the following response:
export interface ProductDetailResponseDTO {
id: number;
categoryId: number;
categoryName: string;
productName: string;
productUrl: string;
shortDesc: string;
thumbImage: string;
isUpcoming: boolean;
}
This interface describes the backend response.
But should our entire frontend application depend on this structure?
Ideally, no.
Instead, define an application-level model.
export interface Product {
id: number;
category: {
id: number;
name: string;
};
name: string;
slug: string;
description: string;
image: string;
upcoming: boolean;
}
Notice the difference.
The backend uses productName, while the application uses name.
The backend uses thumbImage, while the application uses image.
The application model is designed around frontend requirements rather than backend naming conventions.
This creates a useful boundary between external API contracts and internal application data.
4. Mapping Functions: Transforming DTOs into Application Models
Now we need a way to transform the API response into our application model.
This is where mapping functions become useful.
export const mapProductDetailDTO = (
dto: ProductDetailResponseDTO
): Product => ({
id: dto.id,
category: {
id: dto.categoryId,
name: dto.categoryName,
},
name: dto.productName,
slug: dto.productUrl,
description: dto.shortDesc,
image: dto.thumbImage,
upcoming: dto.isUpcoming,
});
The mapper has one responsibility: transforming external data into the format expected by the application.
Why is this useful?
Imagine the backend team changes thumbImage to thumbnailUrl.
Without a mapping layer, multiple components might need updates.
With a mapper, the change can often be handled in one place.
Important: TypeScript interfaces provide compile-time type checking, not runtime validation. If API responses are untrusted, consider validating them with a runtime schema library such as Zod.
5. Repository Pattern: Separating Data Access
Next, let's introduce the repository pattern.
A repository defines how the application accesses data without exposing the underlying data source to the application logic.
First, define an interface.
export interface ProductRepository {
getAll(): Promise<Product[]>;
}
Now create an implementation that communicates with the API.
export class ProductRepositoryImplementation
implements ProductRepository {
async getAll(): Promise<Product[]> {
const response = await fetch("/api/products");
if (!response.ok) {
throw new Error("Failed to fetch products");
}
const data = await response.json();
return data.result.map(mapProductDetailDTO);
}
}
The repository handles:
- API communication.
- HTTP error handling.
- Response extraction.
- DTO mapping.
The rest of the application doesn't need to know how the data is retrieved.
In a larger application, you can also introduce separate API service classes to keep HTTP concerns outside repository implementations.
6. Use Cases: Keeping Application Logic Independent
A use case represents an application operation.
For example, getting all products is an application operation.
export class GetProductsUseCase {
async execute(
repository: ProductRepository
): Promise<Product[]> {
return repository.getAll();
}
}
This might look like an unnecessary additional layer for a simple GET request.
However, use cases become more valuable when application operations involve multiple steps, business rules, authorization checks or coordination between repositories.
The important thing is to introduce them when they provide meaningful separation, not simply to increase the number of files.
7. Connecting Everything Through a Custom React Hook
Now we have our data layer and application layer.
How do we connect them to React?
A custom hook can act as the connection between the presentation layer and application operations.
export const useProducts = () => {
const [products, setProducts] = useState<Product[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const getProducts = async () => {
try {
setLoading(true);
setError(null);
const repository =
new ProductRepositoryImplementation();
const useCase = new GetProductsUseCase();
const result = await useCase.execute(repository);
setProducts(result);
} catch (error) {
setError(
error instanceof Error
? error.message
: "Something went wrong"
);
} finally {
setLoading(false);
}
};
useEffect(() => {
void getProducts();
}, []);
return {
products,
loading,
error,
getProducts,
};
};
Now the component only consumes the hook.
const ProductList = () => {
const {
products,
loading,
error,
} = useProducts();
if (loading) return <p>Loading products...</p>;
if (error) return <p>{error}</p>;
return (
<div>
{products.map((product) => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>{product.description}</p>
</div>
))}
</div>
);
};
The UI no longer needs to know about DTOs, API response structures or repository implementations.
For production applications, this hook should also account for request cancellation, duplicate requests, and React Strict Mode behavior. A data-fetching library can handle many of these concerns when the application requires caching, retries and request deduplication.
8. Suggested Project Structure
As the application grows, a feature-based structure can help keep related files together.
src/
│
├── features/
│ └── products/
│ │
│ ├── domain/
│ │ ├── models/
│ │ │ └── product.model.ts
│ │ │
│ │ └── repositories/
│ │ └── product.repository.ts
│ │
│ ├── application/
│ │ └── use-cases/
│ │ └── get-products.usecase.ts
│ │
│ ├── data/
│ │ ├── dto/
│ │ │ └── product.dto.ts
│ │ │
│ │ ├── mappers/
│ │ │ └── product.mapper.ts
│ │ │
│ │ └── repositories/
│ │ └── product.repository.impl.ts
│ │
│ └── presentation/
│ ├── components/
│ │ └── product-list.tsx
│ │
│ └── hooks/
│ └── use-products.ts
│
├── shared/
│ ├── api/
│ └── components/
│
└── app/
This is only one possible structure. The best architecture depends on application size, team structure and complexity.
9. Is This Architecture Always Necessary?
No.
Not every React application needs a repository, use case, mapper and multiple layers.
For a small landing page or a simple application with a few API requests, a straightforward custom hook may be enough.
However, when working on larger applications with multiple modules, complex API contracts and growing business requirements, separating responsibilities can improve maintainability.
A few principles worth remembering:
- Keep components focused on presentation.
- Avoid coupling UI components directly to backend DTOs.
- Use mapping functions when external and internal models differ.
- Keep data access separate from application operations.
- Introduce abstractions when they solve actual problems.
- Don't confuse more files with better architecture.
Conclusion
Building scalable React applications is not just about writing reusable components.
It is also about understanding where responsibilities belong and how different parts of an application communicate.
DTOs, mapping functions, repositories and use cases provide a structured way to manage that complexity.
You don't need to implement every pattern in every project. Start with the simplest structure that solves the current problem, and introduce additional boundaries as the application evolves.
Good frontend architecture should make future changes easier, not make today's development unnecessarily complicated.
About the Author
I'm Sudarshan K M, a Frontend Developer working with React, Next.js, TypeScript, JavaScript and modern web technologies. I enjoy building responsive, user-focused web applications with attention to UI/UX, maintainable code and scalable architecture.
I'm also expanding my knowledge of backend development with .NET and Node.js.
Explore my work and projects: https://sudarshan07.vercel.app/
Top comments (0)