Best practice for providing current user from db to all react components?

So I know that various auth providers have hooks like useUser() or useSession() which you can use to access their user object in components, but I have a users table where each user has an extensive amount of data describing them. I personally use supabase with the T3 stack, and I don't want to copy all this data to the "user_metadata" that supabase provides just to have the useUser() functionality. So my question is: what's the best practice for providing current user data (from the users table in db) to all react components for the purpose of stuff like conditional rendering? (I've thought about state management solution, or just plain old useContext(), but then how would you trigger refetches when the user changes something?)
7 Replies
Ramsay
Ramsay14mo ago
Same way you'd give your components access to any other data. Create a trpc procedure and call useQuery. Revalidate the query when user data changes.
zendev
zendevOP14mo ago
Sorry I think I wasn’t super clear - I’m talking about providing that data globally to every component in the app, without having to create a bunch of individual queries for every time a component needs that data
Ramsay
Ramsay14mo ago
Right. You create one procedure, then call useQuery in every component that needs the data. Calling useQuery in multiple components does not create a new query every time. It only fetches the data if it's stale, otherwise it uses the cache.
zendev
zendevOP14mo ago
Ohhh really? So if I called the same useQuery in say 10 components rendered on the page, it would still only make one query to the db?
Yiannis
Yiannis14mo ago
Yep that’s correct. This is the blog of one of the core maintainers and he had an excellent article about it! https://tkdodo.eu/blog/react-query-as-a-state-manager I recommend you go through the react query docs and this set of articles side by side if you wanna get into some more advanced usage of react query!
React Query as a State Manager
Everything you need to know to make React Query your single source of truth state manager for your async state
Ramsay
Ramsay14mo ago
And here's another article about how it works. https://tkdodo.eu/blog/inside-react-query calling useQuery many times creates multiple observers, but only creates one query as long as the querykey is the same. The query internally handles request cancellation and de-duplication.
Inside React Query
Taking a look under the hood of React Query
zendev
zendevOP14mo ago
Sweet thanks guys
Want results from more Discord servers?
Add your server