How to build reusable loaders for Remix

Brian Morrison II - Aug 15 - - Dev Community

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:

Image description

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:

Image description

Then import helloLoader and use it in my component:

Image description

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:

Image description

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:

Image description

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player