Remix loaders are server side functions that automatically get executed before the page is rendered.
In certain situations, you may want to load the same data on every page load, such as a user record. Instead of copy/pasta-ing the loader function between all your pages, you can define a loader that can be imported into the routes that need the data.
All loaders have the same basic structure. For example, the following loader will return a simple JSON payload that can be used to render a string on the page:
Since a loader is simply a function, it can be created elsewhere and imported into the page.
For example, I can move βloaderβ into a new file:
Then import helloLoader
and use it in my component:
A real world example
In my use case, I have a web application that's built with Clerk and Convex. On several pages, I need to lookup the user record in Convex using the Clerk user ID and pass that into the page before it starts rendering.
To do this, I have a loader called clerkConvexLoader that gets the Clerk user ID from the Clerk SDK, performs the Convex lookup, and passes that data to the page:
The Convex user record is then available to me before the page even starts loading so I can use it to perform other queries as needed:
Top comments (0)