@tanstack/react-query in layered architecture #8547
Replies: 2 comments 3 replies
-
slightly wrong assumption here. |
Beta Was this translation helpful? Give feedback.
-
|
I've been using Feature-Sliced Design (FSD) in production and here's how I place React Query in that context — though it maps well to any layered architecture.
Query options are framework-agnostic config objects, so they belong in the data layer. In FSD terms, I put them in each feature's // features/user/api/userQueries.ts
export const userQueries = {
detail: (id: string) => queryOptions({
queryKey: ['user', id],
queryFn: () => fetchUser(id),
}),
}
Hooks are React-specific, so they stay in components or custom hooks inside the // features/user/ui/UserProfile.tsx
const { data } = useQuery(userQueries.detail(id))This way your business logic (query keys, fetching logic) stays decoupled from React, and the presentation layer only handles rendering. TkDodo's approach of separating |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello 👋
We are working on structuring our codebase into distinct layers: domain, data, and presentation. However, we’re trying to determine where @tanstack/react-query fits into this architecture.
Here’s where we’re facing challenges:
1️⃣ Domain Layer: This layer should remain technology-agnostic, focusing purely on business logic and rules. Using React Query here would tightly couple our core business logic to a React-specific library.
2️⃣ Data Layer: This doesn’t feel like the right place either, as React Query’s reliance on hooks means that use cases in the domain layer would need to depend on React hooks. This would also violate the principle of keeping the domain layer decoupled from any specific framework or library.
3️⃣ Presentation Layer: This seems like a potential fit for React Query, as it naturally aligns with managing server state in React applications. However, this raises a concern: how do we ensure that the presentation layer consumes repositories or use cases (not raw data-fetching logic) while still leveraging React Query’s features like query invalidation?
Where would you recommend placing React Query in a layered architecture? How can we balance respecting Clean Architecture principles with making the most of React Query’s capabilities?
Thanks for your help! 🙏
Beta Was this translation helpful? Give feedback.
All reactions