Defining Loaders
Add aloader function to your route:
Accessing Loader Data
Use theuseLoaderData hook in components:
Type Safety
Specify the route for full type inference:Loader Context
Loaders receive a context object with useful properties:Using Context
Loader Dependencies
Declare dependencies for cache invalidation:Why Loader Dependencies?
WithoutloaderDeps, loaders only rerun when path params change. With loaderDeps:
- Loader reruns when dependencies change
- Each unique dependency combination is cached separately
- Provides fine-grained cache invalidation
Parallel Loading
Multiple route loaders run in parallel:Sequential Loading
Wait for parent loader data:Caching
Cache Configuration
Control how long data stays fresh:number
default:"0"
Time in milliseconds before cached data is considered stale. Stale data triggers a background refetch but is still used immediately.
number
default:"1800000"
Time in milliseconds before unused cached data is garbage collected (deleted from memory).
Global Defaults
Set default caching behavior:Preloading
Preload route data before navigation:Preload Options
false- No preloading'intent'- Preload on hover/touch'viewport'- Preload when link visible'render'- Preload when link renders
Per-Route Preloading
Manual Preloading
Before Load
Run code before the loader:beforeLoad vs loader
beforeLoad: Runs first, sequential, can add contextloader: Runs after, parallel across routes, for data fetching
beforeLoad for:
- Authentication checks
- Authorization logic
- Redirects
- Adding context for loaders
loader for:
- Fetching data
- Data transformations
- API calls
Error Handling
Handle loader errors gracefully:Catching Errors
Invalidation
Force loaders to rerun:Deferred Data
Start rendering before all data loads:Should Reload
Control when loaders rerun:Loader Patterns
Global Data
Dependent Requests
Parallel Requests
Next Steps
Type Safety
Configure end-to-end type safety for loaders
Search Params
Use search params in loader dependencies
Path Params
Access path parameters in loaders
Navigation
Navigate with preloading