Clean architecture
- React Native course
- Expert
- Lesson 15/47
- 5 min
Learn clean architecture principles.
Clean architecture
Clean architecture is an approach where dependencies flow inward. At the center sit the domain (entities and use cases); on the outside, frameworks and UI. The outer ring depends on the inner; never the reverse.
This way the domain logic is independent of React Native or the database. Even if the framework changes, the domain stays the same; tests are easy to write. Dependencies are inverted (dependency inversion).
Dependency inversion
The core principle of clean architecture is dependency inversion. The outer layer depends on the inner; the inner does not know the outer. This is achieved through interfaces.
Example: a UserRepository interface is defined in the domain; the real implementation (API call) is written in the outer layer. The domain does not know the concrete class; it only calls the interface.
Practice UserRepository interface
Define a UserRepository interface. It should have a method getUser(id: string): Promise<User>. Also define User as a simple interface.
Starter code
// Define User and UserRepository types here
export { User, UserRepository };Sample solution
// Define User and UserRepository types here
interface User {
id: string;
name: string;
}
interface UserRepository {
getUser(id: string): Promise<User>;
}
export { User, UserRepository };Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Clean rings
| Term | Meaning |
|---|---|
Entities |
Domain entities |
Use cases |
Business logic |
Controllers |
UI adapters |
Frameworks |
React Native, database |
2 What does the domain know in clean architecture?
- Only its own entities and use cases
- React Native components
- The database schema Correct answer
- HTTP requests
Explanation: The domain only knows its own entities.
3 Write the repository interface name
interface ____ {
getUser(id: string): Promise<User>;
}
interface UserRepository {
getUser(id: string): Promise<User>;
}
Explanation: UserRepository is defined in the domain.