All files / src/hooks use-route-prefetching.ts

64.7% Statements 11/17
25% Branches 1/4
57.14% Functions 4/7
64.7% Lines 11/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                1x 2x     2x 1x       2x 1x 6x     1x                   2x       2x       1x                                                
import { useEffect, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import {
  intelligentPrefetch,
  prefetchOnInteraction,
  routes,
} from '@/lib/route-prefetcher';
import {
  AUTH_ROUTES,
  DASHBOARD_ROUTES,
  WALLET_ROUTES,
  STATS_ROUTES,
  PROFILE_ROUTES,
} from '@/constants/route';
 
// Hook for managing route prefetching
export const useRoutePrefetching = () => {
  const location = useLocation();
 
  // Initialize prefetching on app start
  useEffect(() => {
    intelligentPrefetch();
  }, []);
 
  // Prefetch related routes based on current location
  useEffect(() => {
    const currentRoute = routes.find(route =>
      location.pathname.startsWith(route.path)
    );
 
    Iif (currentRoute) {
      // Prefetch likely next routes based on current page
      const relatedRoutes = getRelatedRoutes(location.pathname);
      relatedRoutes.forEach(routePath => {
        prefetchOnInteraction(routePath);
      });
    }
  }, [location.pathname]);
 
  // Function to manually trigger prefetching for specific routes
  const prefetchRoute = useCallback((routeName: string) => {
    prefetchOnInteraction(routeName);
  }, []);
 
  return { prefetchRoute };
};
 
// Define related routes for intelligent prefetching
const getRelatedRoutes = (currentPath: string): string[] => {
  const routeRelations: Record<string, string[]> = {
    [AUTH_ROUTES.LOGIN]: [DASHBOARD_ROUTES.OVERVIEW], // After auth, users likely go to overview
    [DASHBOARD_ROUTES.OVERVIEW]: [
      WALLET_ROUTES.WALLET,
      WALLET_ROUTES.TRANSACTIONS,
    ], // From overview, users often go to wallet or transactions
    [WALLET_ROUTES.WALLET]: [
      WALLET_ROUTES.TRANSACTIONS,
      DASHBOARD_ROUTES.OVERVIEW,
    ], // Wallet users often check transactions
    [WALLET_ROUTES.TRANSACTIONS]: [
      WALLET_ROUTES.WALLET,
      STATS_ROUTES.STATISTICS,
    ], // Transaction users might check wallet or stats
    [STATS_ROUTES.STATISTICS]: [
      WALLET_ROUTES.TRANSACTIONS,
      DASHBOARD_ROUTES.OVERVIEW,
    ], // Stats users might go back to transactions or overview
    [PROFILE_ROUTES.SETTINGS]: [], // Settings is usually a destination, not a starting point
  };
 
  return routeRelations[currentPath] || [];
};