Nehal Damania
Nehal Damania

Reputation: 9008

Project Structure for a CRA React Project with React Query

We are starting with a new React Project using CRA. And, are planning to use React Query.

Need help on the folder structure for the project. Any advantage of having feature based folder structure vs. file type based structure?

Also, Any advantage of having service/API with only the axios/fetch call and creating useQuery/useMutation hook directly in component? vs. creating custom Hooks for each reactQuery?

// API call in a service file and using that API call in the component
export const fetchPost = (key, postId) =>
  axios.get(`/api/posts/${postId}`).then((res) => res.data)

//Custom Hooks for each API call in a service 
export default function usePost(postId) {
  return useQuery(postId && ['post', postId], fetchPost)
}

Upvotes: 4

Views: 6413

Answers (1)

TkDodo
TkDodo

Reputation: 28833

Any advantage of having feature based folder structure vs. file type based structure?

I totally prefer feature based folders. They will co-locate code belonging to your feature in the feature directory and make it easier to reason about where specific things, especially queries, are used. Most queries only "belong" to one feature - if you need a query in many features, you can still move it up to a top-level queries directory. But having only queries, utils and components as directories makes it incredibly hard to see what is used where.

I can recommend this article: https://kentcdodds.com/blog/colocation

regarding custom hooks: It's almost always good to create custom hooks. I keep the actual fetch-functions next to the query function, but not exported. Something like:

in: 
features
  - posts
    - queries.ts

const fetchPost = () => ...

export const usePost = (id) => useQuery(...)

with this:

  • You can keep the actual data fetching out of the ui, but co-located with your useQuery call.
  • You can keep all usages of one query key (and potentially type definitions) in one file.
  • If you need to tweak some settings or add some data transformation, you can do that in one place.

Upvotes: 10

Related Questions