T
TanStack4w ago
xenial-black

Performance Question. useQuery in each component or pass the data in as a prop to each?

From a performance standpoint, if I have a list of 500 items that all need a big object that is in the query cache, is it better for me to have a useQuery call in each of the 500 components or have one call in the parent and pass the whole object as a prop to each of the 500 items.
2 Replies
quickest-silver
quickest-silver4w ago
I usually try to find a chokepoint where 2 or 3 components use the same query, and then I pass it as a prop to them. On the other hand, if you have to pass more than 2 levels deep, you will face what is called a props drilling. That's when you simply pass some prop 3 or more levels deep down the components tree to the child that actually uses it. That's also a bad thing, because you bloat your intermediate components just to pass that prop. In this case, it's better to use a query inside a component that actually needs it. Performance-wise, I don't think extra useQuery will introduce some overhead as it's very performant and optimized. You will allocate extra resources for useQuery observers, but it shouldn't be a huge problem. The data itself is cached and shared across all useQueries that subscribe to the same key, so it's not duplicated. If you structure your components well, you will be free to choose from either option and shouldn't face any issues. And remember, there's no silver bullet. It's always a tradeoff between one or another. One more thing to consider is whether you want a component to be presentational or self-sufficient. For example, your component uses some pieces of data from the query, but those pieces may come from different queries on different pages. In that case, you want to decouple useQuery from the component and pass that data as props. Another case is when you have an edit form that is used on multiple pages. The edit form will use the same data no matter the page, so it's tightly related to that data, and it's just easier to use a query inside the form component. Then you can simply import it on a page as a single cohesive unit, with all the data it needs to work.
optimistic-gold
optimistic-gold4w ago
discussed lately in #Only update affected post in infinite feed? - useQuery per component prevents re-renders in big lists

Did you find this page helpful?