Is there any need to use Context API with React Query? #3859
-
Hey there, I have seen some patterns lately where folks seem to use the Context API to pass data retrieved from React Query down to child components. Personally I tend to use From reading this stack overflow answer, it sounds like my approach is preferred, but I was wondering if there is any case whatsoever where using Context API along with React Query would make more sense? The only thing I can think of is perhaps if the user changes some filters (like car color) in a top level component, you may want an easier way to pass that down instead of prop drilling, and then use that filter as a key inside useQuery to perform a refetch? Are there any other specific reasons why custom hooks would be preferred over Context API? Would it prevent more re-renders? Just looking to get some opinions. It might simply just be a pattern preference. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I personally only use the Context API to manage layout state and sometimes form state if the forms are big and complex. |
Beta Was this translation helpful? Give feedback.
-
I might be biased since I wrote the StackOverflow answer, so I usually prefer to call the custom useQuery hook whenever I need to. It does create more observers and timers, so if you have like 1000 of them, there have been reports of performance hits (e.g. on a 6x slowdown in chrome). Putting data from react-query into the context api is not the worst idea though - it's just a decoupling of some sorts, just like prop drilling. consider:
in this case, you can either just call I think this is a valid use-case, and it's also not the usual state-syncing anti-pattern, as the single source of truth is still the query itself (or whatever other source we have for that context). All background updates of RQ will also still work because the Parent will re-render, and the child will get that update. One thing to keep in mind is to memoize the children to the Provider to avoid unnecessarily re-rendering the whole tree, and you also cannot do fine grained subscriptions like you can do with e.g. the |
Beta Was this translation helpful? Give feedback.
I might be biased since I wrote the StackOverflow answer, so I usually prefer to call the custom useQuery hook whenever I need to. It does create more observers and timers, so if you have like 1000 of them, there have been reports of performance hits (e.g. on a 6x slowdown in chrome).
Putting data from react-query into the context api is not the worst idea though - it's just a decoupling of some sorts, just like prop drilling. consider: