React Router V6 Async Route Loader

6.6k Views Asked by At

Have been checking out React Location and it has a very useful feature (Asynchronous Routing, Prefetching) and am wondering if this is possible in React Router V6. For example, they support Async Route Loaders

const routes = [
   {
     path: 'teams',
     loader: async () => ({
       teams: await fetch('/api/teams'),
     }),
     children: [
       {
         path: ':teamId',
         loader: async ({ params: { teamId } }) => ({
           team: await fetch(`/api/teams/${teamId}`),
         }),
       },
     ],
   },
 ]

I am sure it could be done (or added) since something similar is done with Remix Run.

Oh and also when is this happening (from reactrouter.com)?

We recommend waiting for the backwards compatibility package to be released before upgrading apps that have more than a few routes.

2

There are 2 best solutions below

0
On

This type of loader behavior is coming in [email protected] which should have an alpha release very soon! See https://remix.run/blog/remixing-react-router for more info about the changes being ported over from Remix.

The backwards compatibility package was also recently released - have a look at https://remix.run/blog/react-router-v6.3.0 for more info.

Hope this helps!

0
On

I created a workaround for async loading for React Router: react-router-loading.

But it works a bit differently. Instead of passing fetchers to routes, you need to tell the router when to switch pages using the context in components:

// PageComponent.jsx

import { useLoadingContext } from "react-router-loading";
const loadingContext = useLoadingContext();

const loading = async () => {
    // loading some data

    // call method to indicate that loading is done and we are ready to switch
    loadingContext.done();
};