Design Patterns · Middle · Question 17 of 75
Why have a layer of "repositories" or API services on the frontend instead of calling fetch directly in components?
- ✓Correct answer: Components don't know about transport and API format, which is easy to replace and mock
- 2Without a separate layer, the browser doesn't allow caching server responses
- 3It's a React requirement:
fetchcan't be called inside components
Explanation
A repository hides where data comes from (REST, GraphQL, cache, mocks) and returns domain objects. When an endpoint changes, one place is edited, and tests replace the whole repository. TanStack Query hooks often call exactly such functions.