Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created February 10, 2020 12:31
Show Gist options
  • Save sibelius/56d2d353a2bee88c90a851a07e744ca5 to your computer and use it in GitHub Desktop.
Save sibelius/56d2d353a2bee88c90a851a07e744ca5 to your computer and use it in GitHub Desktop.
usePreloadRoute to preload code or data based on events
import { useCallback } from 'react';
import { matchRoutes, MatchedRoute, RouteConfig } from 'react-router-config';
const prepareMatches = <Params extends { [K in keyof Params]?: string }>(matches: Array<MatchedRoute<Params>>) => {
return matches.map(match => {
const { route, match: matchData } = match;
const prepared = route.prepare ? route.prepare(matchData.params) : {};
const Component = route.component.get();
if (Component == null) {
route.component.load(); // eagerly load
}
return { component: route.component, prepared, routeData: matchData };
});
};
const preloadCode = (pathname: string) => {
// preload just the code for a route, without storing the result
const matches = matchRoutes(routes, pathname);
matches.forEach(({ route }) => route.component.load());
};
const preload = (pathname: string) => {
// preload the code and data for a route, without storing the result
const matches = matchRoutes(routes, pathname);
prepareMatches(matches);
};
export const usePreloadRoute = (to: string) => {
const router = useRoutingContext();
// Callback to preload just the code for the route:
// we pass this to onMouseEnter, which is a weaker signal
// that the user *may* navigate to the route.
const preloadRouteCode = useCallback(() => {
router.preloadCode(to);
}, [to, router]);
// Callback to preload the code and data for the route:
// we pass this to onMouseDown, since this is a stronger
// signal that the user will likely complete the navigation
const preloadRoute = useCallback(() => {
router.preload(to);
}, [to, router]);
return [preloadRouteCode, preloadRoute];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment