Data Loading

Explanation#

When a user navigates to one of your routes, the application will not re-render until a response has been created. If the route that matches has a match function that makes a request to the server, the re-render will be delayed, possibly giving the user the impression that nothing is happening.

The <Prefetch> component lets you load data prior to navigating to a route. This uses the prefetch route interaction and the IntersectionObserver API to load data for a route when a specified element is visible in the page. This example uses <Link>s so that when the associated <a> element is visible, the data will be fetched.

import prefetch from "@curi/route-prefetch";

const router = curi(history, routes, {
  route: [prefetch()]
});

<Prefetch match={{ name: "Album", params: { id: 1 } }}>
  {ref => (
    <Link to="Album" params={{ id: 1 }} ref={ref}>
      Album 1
    </Link>
  )}
</Prefetch>
// when <a href="/a/1">Album 1</a> is visible,
// the data for that route will be loaded

Live Demo#

Use the three buttons at the top of the Sandbox to toggle view modes. Clicking the menu button in the top left corner opens a menu to switch between files.

On GitHub#

If you want to run this code locally, the source code is available on GitHub here.