-
-
Save jgcmarins/0e075b0e9937696e07d1f23956b0edcb to your computer and use it in GitHub Desktop.
usePreloadRoute to preload code or data based on events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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