React Router Loader Functions Explained: A Simple Overview

React Router Loader Functions Explained: A Simple Overview

·

2 min read

The basic idea of a loader function is that it lets you fetch data before rendering your route.

In other words:

  1. A user navigates to a page

  2. A loader runs to fetch data for that page

  3. The page’s component renders with the fetched data

React Router is built on browser standards

Loader functions are no exception! Since this is the case, it's common to return web Responses from a loader function. To make this easier, the library provides a json utility for when you need to return a JSON payload from a request.

Keep in mind that React Router works by intercepting requests made to your server and sending intercepted GET requests to your loader functions. From there, you have better control over the client-server interaction.

An example is worth 1000 words, so let's jump right in!

In the example below, we have a Home route and a Projects route. Each route has an associated loader function that returns a Response for that route.

As you click each link, notice the slight delay before the next page renders. This is from the sleep utility in each of the loader functions. In other words, the loaders return their data, and then the page is rendered.

To help demonstrate this, a loading message appears in the top right corner when any loader function is executing.