Custom Data Strategies
ThedataStrategy API allows you to customize how React Router executes loaders and actions, giving you control over when and how data is fetched.
Overview
By default, React Router calls loaders in parallel and actions individually. ThedataStrategy function lets you override this behavior to implement patterns like:
- Sequential loader execution
- Single fetch requests for all loaders (like Remix’s Single Fetch)
- Middleware patterns with context passing
- Custom error handling and response decoding
Basic Usage
The dataStrategy Function
ThedataStrategy receives a DataStrategyFunctionArgs object:
Matches and resolve()
Each match in thematches array has a resolve() method that:
- Waits for
route.lazyto load if needed - Determines whether to call the loader or action
- Handles
shouldRevalidatelogic internally - Returns a
HandlerResultwith the data or error
Sequential Loaders
Execute loaders one at a time, passing context between them:Middleware Pattern
Implement middleware that runs before loaders:Single Fetch Pattern
Make one request for all loaders:Custom Response Decoding
Decode responses using custom formats:Error Handling
Theresolve() method never throws. Errors are returned in the result:
Working with Actions and Fetchers
ThedataStrategy handles actions and fetchers too. For single-match operations, you’ll receive a single-item array:
Framework Mode
In framework mode, configuredataStrategy via createRequestHandler:
Best Practices
- Don’t modify request/params: The handler receives its own arguments
- Use resolve() callbacks sparingly: Only when you need custom logic
- Handle shouldRevalidate: It’s already handled by
resolve() - Consider performance: Sequential loading can slow down your app
- Test both states: With and without interruptions