Design Patterns Applied in React
This document explains Martin Fowlerβs design patterns and how they can be applied in React applications.
1. MVC (Model-View-Controller)
- View β React Components / Pages
- Controller β Business Logic Hooks
- Model β State (Zustand/Redux) or backend data
2. Repository Pattern
- Abstracts API and database access
- Example:
transactionService.jsfetches and formats data
3. Observer / Event-Driven
- React components react to state changes
- Example: Global notifications using Zustand or Redux
4. Dependency Injection
- Pass services/hooks via props or Context
- Makes components testable and decoupled
Example
1. Data Mapper
- Maps API response to frontend model
- Example:
const mapTransaction = (apiData) => ({
id: apiData.id,
amount: parseFloat(apiData.amount),
category: apiData.categoryName,
});
2. Lazy Load / Pagination
- Infinite scroll, cursor pagination
- Optimizes performance
3. Caching
- Use RTK Query, SWR, or React Query
- Reduces repeated network calls