Nick
Nick16mo ago

Mutations and Queries in React Contexts causing unexpected behaviors

In my organization, we recently moved to put all of our mutations/queries into React Contexts and out of components (NextJS with React 18). I am now seeing requests and debouncing behaviors that used to work no longer work.
In some cases it appears we now have race conditions as loading/success are not necessarily being handled, but in other cases we're not getting reactivity from mutations that are in contexts Anyone else have experience or tips re: throwing tRPC stuff into React Contexts?
6 Replies
Nick
Nick16mo ago
This sounds more of a React Query issue, rather than with the tRPC integration And also likely, it's a PEBCAK for React and React Query
Nick
Nick16mo ago
What I am seeing is after getting moved to Context, these mutations are always idle, as they're apparently being reconstituted on re-render
Nick
Nick16mo ago
There's probably no need to hoist up into contexts, React Query already does caching in a context, and if you need to fix waterfalls you can use RQ's prefetch method Ah yes, each useMutation will be its own instance I think and react has some footguns around Context where you could accidentally be re-mounting your entire tree repeatedly put in
useEffect(() => console.log("MOUNT"), [])
useEffect(() => console.log("MOUNT"), [])
and see if you get multiple MOUNT logs in some compnents
Nick
Nick16mo ago
yeah getting two mounts on a page that is reliant on context
Nick
Nick16mo ago
So long as it doesn’t remount when triggering the mutations or queries you’re probably okay React in strict mode does some remounting fun to show up bugs for you, so twice on first render isn’t a big deal
Nick
Nick16mo ago
interesting behavior: a mutation with an onSuccess redirect is always idle when i pull it from context and use it on a page, but if i hit "Back" on the page that mutation redirects me to, the fired-off mutation is pulled from the context with "isSuccess: true"