r/reactjs • • 15d ago

Discussion How do you structure feature-based React apps with Zustand, TanStack Query, providers, and business logic?

Hey everyone! πŸ‘‹

I'm trying to establish a clean, reusable feature-based architecture for React/TypeScript apps, especially when using Zustand + TanStack Query.

I'm working on a visual editor that fetches documents from an API, initializes a Zustand editing session, and will eventually handle canvas state, selection, history, saving, etc.

I'm considering this structure:

features/editor/
β”œβ”€β”€ components/
β”œβ”€β”€ hooks/
β”œβ”€β”€ store/
β”‚   β”œβ”€β”€ editor-store.ts
β”‚   β”œβ”€β”€ editor-store-provider.tsx
β”‚   └── slices/
β”‚       β”œβ”€β”€ document-slice.ts
β”‚       β”œβ”€β”€ selection-slice.ts
β”‚       └── history-slice.ts
β”œβ”€β”€ queries/
β”œβ”€β”€ domain/      ?
β”œβ”€β”€ utils/       ?
β”œβ”€β”€ lib/         ?
└── services/    ?

I'd love to know how you handle a few things in production:

  1. API / queries: Where do raw API functions go? Do you separate them from TanStack Query options/hooks? Do you organize queries by feature or shared domain?
  2. Zustand: Do you keep providers alongside stores? When do you introduce slices vs multiple stores?
  3. Business/domain logic vs utilities: This is probably what I'm most unsure about. Where do you put pure functions containing actual application logic, independently of React, Zustand or API calls? For example: Would a domain/ directory make sense here? For example, domain/geometry.ts for canvas calculations, domain/document.ts for document manipulation, etc. Or would you simply use utils/, lib/ or services/? How do you distinguish business/domain logic from generic utility functions? Is a dedicated domain/ folder a useful convention, or does it introduce unnecessary complexity?

    • Formatting an aspect ratio.
    • Calculating canvas geometry, scaling or snapping.
    • Validating editor-specific constraints.
    • Transforming or manipulating document data.
  4. Shared code: When do you move something out of a feature into a shared location? Do you prefer shared domain modules or global utilities?
  5. Server vs local state: Would you fetch with TanStack Query, initialize Zustand from the result, then keep local edits separate from the query cache? How do you avoid overwriting unsaved changes on refetch?

I'm not looking for a strict architecture or lots of abstractions, just practical conventions that stay maintainable as projects grow.

If you have real-world folder structures or examples, I'd love to see them. Thanks! πŸ™

39 Upvotes

20 comments sorted by

17

u/Cordes96 15d ago edited 15d ago
  1. I separate them out into query keys so that I can re use the query keys across the application without needing to import hooks, and also it allows me to invalidate queries without having to do anything extra beyond importing the query keys across features, which end up in a shared api folder either in a package or in shared/api to avoid cross-feature imports and the hooks stay in the feature.

    1. Also a side note. Query keys don't require react unlike hooks so if you use this in a mono repo you can use the query keys across multiple applications that have different javascript frameworks and still be able to build the same api endpoints.
  2. These stay in features unless used in multiple features; then the required pieces are pulled up into their own reusable store in shared/stores.
  3. My repo is a monorepo, and I build them out into a utility library or put shared utility files in shared, or if they are local, in a feature/utils folder.
  4. Anything that can be built into a feature and then used in composition, I do so thatt way the feature logic is contained, but I can pass components into other components via composition, as I use the top-level routing page to handle my composition of components.
  5. TanStack Query is the source of truth for the server, and Zustand is the source of truth for the UI try to avoid put copies of values from TanStack Query into Zustand; instead, use form libraries if you are editing it, and only put the value to identify the object from the TanStack Query into Zustand if you don’t need to do work on that value inside a store or have it read from some other component in that feature; useState is way easier to use.

These are my opinions, but I have 8 YoE as a software architect/consultant on large frontend monorepos, and these are the most scalable methods I have found without getting super overcomplicated or re inventing the wheel.

1

u/musHeaer 11d ago

100% agree on using top level route pages for composition, keeps the individual features way cleaner.

1

u/GeekyAntsBFSI 14d ago

A practical starting point:

features/editor/
  api/documents.ts
  queries/document-options.ts
  store/editor-store.ts
  store/editor-provider.tsx
  domain/geometry.ts
  domain/document.ts
  components/

domain/Β holds pure editor rules;Β utils/Β holds generic helpers. Keep providers beside stores, add slices when needed, and share code once another feature needs it.

TanStack Query owns server data; Zustand owns the editing draft. Initialize once per document session. Refetches should flag newer versions, never overwrite unsaved edits.

1

u/CaptainZiboo 14d ago

So the main logic must go into /domain ? how about /api and /queries, what would be the difference / purpose of those 2 folders?

1

u/rsajdok 11d ago

2

u/CaptainZiboo 11d ago

Imma check that ! Thank you ! πŸ™

1

u/DVR_Design 14d ago

For the unsaved changes part, I'd treat the query cache as the last saved snapshot and keep the Zustand session as a separate draft. Initialize the store once per document id (key the provider on the id), and on refetch only rehydrate if the draft isn't dirty, otherwise hold the new server version aside and show a "this changed on the server" prompt. Keep a baseVersion or updatedAt in the store so a save can be rejected or merged when the server moved underneath you. Setting a high staleTime and turning off refetchOnWindowFocus for the editor query also removes most surprise refetches. On folders, a domain/ dir for pure stuff like geometry and snapping is worth it mostly because those are the easiest things to unit test without React.

1

u/Mamad-mirza-dev 5d ago

The structure you have is close β€” I'd just draw the lines a bit harder. 1) Keep the raw API functions in features/editor/api/ as plain functions with no React in them, then put the TanStack Query wrappers in a separate queries file next to them. That way the query options are reusable and the API layer stays testable on its own. 2) One Zustand store per feature, with slices inside it if it grows β€” I wouldn't add a provider per store. A provider only earns its place when you genuinely need per-instance state, like two editors on the same page; otherwise a plain store is simpler and avoids re-render traps. 3) Domain logic (geometry, your document model) goes in features/editor/domain/ as pure functions with no React imports. Utils is only for genuinely generic helpers, and lib/services is for cross-cutting infra like auth or storage. 4) Only move code to src/shared/ when a second feature actually imports it β€” pulling it out early is how you end up with a shared folder full of things only one feature uses. 5) Treat TanStack Query as the source of truth for server state, and keep Zustand for local UI and editing state only. Fetch with a query, hydrate the editor from it, and push changes back with mutations β€” duplicating server data into Zustand and trying to keep the two in sync is where most of the pain comes from.

-4

u/Any-Ring6621 14d ago

The AI does it

0

u/robert2209 12d ago

Best to keep this out of the AI flow and think about it

1

u/Any-Ring6621 12d ago

It was a joke

0

u/Mysterious-Law-3416 15d ago

/api inside editor
keep zustand and providers in stores folder
/utils for util funcs, /schemas for zod schemas
/shared inside /features
depends

-1

u/karmatics29 15d ago

I'd keep three layers apart. Raw API functions live in a plain api file per feature, returning typed data with no React. Query options (queryKey plus queryFn) wrap those, and hooks just call useQuery with them.

A domain/ folder is fine if it holds pure functions with no imports from React, Zustand or fetch: geometry, snapping, document transforms, constraint validation. Those are trivial to unit test. Keep utils/ for generic helpers like formatting an aspect ratio string.

For server versus local state, treat the query result as the baseline and initialize the Zustand session once from it, keyed by document id. Set refetchOnWindowFocus to false for that query, or skip syncing while the store has a dirty flag. Compare a server version or updatedAt on save to catch conflicts. Use slices while they share one undo history and selection model, and split stores only when lifecycles differ.

1

u/CaptainZiboo 14d ago

So basically

/domain = logic
/api = pure api requests
/queries = react query wrappers for /api functions

right ?

1

u/Cordes96 14d ago

Not op, but domain folders are always interesting as that means you have domain logic being separated from the component, which in theory could be mostly solved with composition, not even needing to separate out logic into its own folder. And if it needs to be re used then it’ll end up being a hook or a generic utility file. I rarely get to the point of using domain folders, tbh, and I have built giant repos with hundreds of features and still rarely get to /domain, but I have always opted for using hooks for most of my containerization of logic, but a /domain folder does work if you want to keep that logic in a isolated way, but I’d love to see an example of what you plan to put in there.

But for the /api and /queries, that depends on how you want to use React Query.
There was a time when people really opted for putting useQueries inside a wrapper hook, but now the go-to implementation is to build out the QueryOptions as a pure function as they end up being pure JS and then pass that to useQuery either from a wrapper library or from the TanStack Query library itself.
Like const test = useQuery(testQueryOptions);

So if you go by this implementation, you’ll only need one folder to hold your QueryOptions, but it seems like most people end up using /api.
This would also mean that your mutations would just be react hooks ending up in your /hooks folder