Lesson 7 of 10
Clean Architecture for Mobile
Clean Architecture separates the business logic from UI and infrastructure concerns. The core domain has no knowledge of React Native, navigation, or API calls. This makes the business logic independently testable and portable (same domain, different UI).
Domain Layer - Pure Business Logic
// Domain layer: zero React Native imports
// src/domain/
// ---- Entity ----
// Pure data + invariants (no class needed in TypeScript)
export interface Order {
id: string;
items: OrderItem[];
status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled';
total: number;
createdAt: Date;
}
export interface OrderItem { productId: string; quantity: number; unitPrice: number; }
// ---- Use Case (Application Layer) ----
// Orchestrates business rules - no UI, no axios
export interface OrderRepository {
findById(id: string): Promise<Order | null>;
findByUserId(userId: string): Promise<Order[]>;
save(order: Order): Promise<void>;
}
export class CancelOrderUseCase {
constructor(private readonly orderRepo: OrderRepository) {}
async execute(orderId: string, userId: string): Promise<{ success: boolean; error?: string }> {
const order = await this.orderRepo.findById(orderId);
if (!order) return { success: false, error: 'Order not found' };
if (order.status === 'shipped' || order.status === 'delivered') {
return { success: false, error: 'Cannot cancel - order already shipped' };
}
const cancelled: Order = { ...order, status: 'cancelled' };
await this.orderRepo.save(cancelled);
return { success: true };
}
}
// ---- Infrastructure Layer - implements domain interfaces ----
// src/infrastructure/repositories/OrderRepositoryImpl.ts
export class OrderRepositoryImpl implements OrderRepository {
constructor(private readonly apiClient: AxiosInstance) {}
async findById(id: string): Promise<Order | null> {
const { data } = await this.apiClient.get<Order>(`/orders/${id}`);
return data;
}
async findByUserId(userId: string): Promise<Order[]> {
const { data } = await this.apiClient.get<Order[]>(`/users/${userId}/orders`);
return data;
}
async save(order: Order): Promise<void> {
await this.apiClient.patch(`/orders/${order.id}`, order);
}
}
// ---- Presentation Layer - React Native component ----
// Depends on use case, knows nothing about repository implementation
function CancelOrderButton({ orderId, userId }: { orderId: string; userId: string }) {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
async function handleCancel() {
setIsLoading(true);
const repo = new OrderRepositoryImpl(apiClient);
const useCase = new CancelOrderUseCase(repo);
const result = await useCase.execute(orderId, userId);
setIsLoading(false);
if (!result.success) setError(result.error ?? 'Failed');
}
return (
<Pressable onPress={handleCancel} disabled={isLoading} style={{ backgroundColor: '#dc2626', padding: 14, borderRadius: 10 }}>
<Text style={{ color: 'white', fontWeight: '700' }}>{isLoading ? 'Cancelling...' : 'Cancel Order'}</Text>
</Pressable>
);
}Dependency Injection with a Service Locator
// Simple service locator for mobile (no heavy DI framework needed)
// src/infrastructure/container.ts
import { apiClient } from '@shared/services/apiClient';
import { OrderRepositoryImpl } from './repositories/OrderRepositoryImpl';
import { CancelOrderUseCase } from '@domain/usecases/CancelOrderUseCase';
import { PlaceOrderUseCase } from '@domain/usecases/PlaceOrderUseCase';
// Singleton instances
const orderRepo = new OrderRepositoryImpl(apiClient);
// Use cases are cheap to create (stateless)
export const useCases = {
cancelOrder: () => new CancelOrderUseCase(orderRepo),
placeOrder: () => new PlaceOrderUseCase(orderRepo),
};
// In tests: swap the repository for a mock
// const mockRepo: OrderRepository = { findById: jest.fn(), findByUserId: jest.fn(), save: jest.fn() };
// const cancelOrder = new CancelOrderUseCase(mockRepo);Tip
Tip
Practice Clean Architecture for Mobile in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Separating Presentation, Domain use cases, and Data repositories in mobile apps
Practice Task
Note
Practice Task - (1) Write a working example of Clean Architecture for Mobile from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Clean Architecture for Mobile is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?