james emanon
james emanon

Reputation: 11807

react-query and selectors and architecture

I am removing some very intertwined global state from a new app (redux/sagas/selectors), to -> context api and react-query. There are tons of selectors integrated into this "global state", that is now needing to be refactored. I've only put a few, co-locating them with the mutations that generate the required data. BUT --

What are your strategies of using "selectors" with react-query?

Where are you locating these selectors, in the component folder or in a "selectors" folder, or sitting within the react-query useQuery in which the data is derived?

So, just to be clear, I am using the new react-query selector functionality. My legacy APP has selectors globally & in the components proper, and I am not sure that is the clearest way.. also, especially if I have a useQuery wrapper sitting globally... just trying to sort out the architecture here.

Any help is appreciated.

Note: I guess we could have a "selectors" file (co-located) with the feature, but do we then import the useQuery hook I have and just do it there.. in a "selectors.ts" file IN the feature folder it is used in..... OR move the selectors INTO the useQuery wrapper hook file.

  1. What if these selectors are feature dependent (no other feature/part of the is gonna need them?).
  2. What if these selectors can be used globally?

Strategies?

Upvotes: 1

Views: 1549

Answers (1)

TkDodo
TkDodo

Reputation: 28833

I personally try to keep as little things as possible global - mostly things co-located within a certain feature. If something really needs to be accessible everywhere in the app, it's likely it's own feature. If there is a single query that needs to be used in multiple features, I do have a top level queries directory where they are, but there is really not much in there.

As for selectors: I inline them in the useQuery hook, if I need them more than once, I extract them to a function, and if that's get out of hand, I put them in a separate file next to the queries, like:

- features
  - todos
    - queries.ts
    - selectors.ts

nothing fancy just going with whatever Kent C. Dodds recommends :) https://kentcdodds.com/blog/colocation

Upvotes: 1

Related Questions