T
TanStack4mo ago
eastern-cyan

Is refactoring global React context provider to a loader bad practice?

I'm currently going through the documentation, and I see that loaded data can be accessed from within components as well. At the moment, I have a React context that loads user profile data as well as localization. Everywhere I need it, I access it using useUserProfile. Does it make sense to refactor this to a loader at root level, and then to access that data from whichever route you're in? Is that bad practice?
3 Replies
unwilling-turquoise
unwilling-turquoise4mo ago
Would make sense, just keep in mind that loaders run in parallel. So if child loaders need to have that information, you can query that information in a beforeLoad and put it into the context. This is how most of the Auth examples handle user info. If you have to share the same data across many components, it might be better to use an independent query solution like tanstack query. This makes the data dependency of a route more explicit.
eastern-cyan
eastern-cyanOP4mo ago
I see! We're already using tanstack query, so if delegating it to that works well with the router, that's fine by me!
ratty-blush
ratty-blush4mo ago
One downside that comes to mind is that you will need to run router invalidation in order to change that data, and recalculate router context/loader values, while React context are reactive by nature and can encapsulate how you edit the values. Unless you have a specific need, I don’t think is worth it

Did you find this page helpful?