Loaders and Actions
Loaders and actions are the primary way to load and mutate data in React Router. They run on the server in Framework mode and enable powerful patterns like optimistic UI, automatic revalidation, and error handling.Loaders
Loaders fetch data before a route renders. They’re called before your component renders, ensuring data is ready immediately.Basic Loader
Loader Function Signature
Fromlib/router/utils.ts, loaders receive LoaderFunctionArgs:
Accessing Request Data
Loaders receive a standard Web Fetch API Request:Returning Data
Loaders can return various response types:Error Handling in Loaders
ErrorBoundary.
Actions
Actions handle data mutations triggered by form submissions or imperative calls.Basic Action
Action Function Signature
Handling Form Data
Different HTTP Methods
Returning Action Data
Action data is available viauseActionData:
Data Flow
The complete data flow for navigation and mutations:Revalidation
After an action completes, React Router automatically revalidates loaders to keep UI in sync.Automatic Revalidation
Controlling Revalidation
You can prevent revalidation when it’s not needed:lib/router/router.ts, the shouldRevalidate function receives:
Manual Revalidation
Parallel Data Loading
React Router loads all matching route loaders in parallel:Context and Request Context
In Framework mode, you can provide context to loaders and actions:Redirects
Redirecting from loaders and actions:lib/router/utils.ts, redirect creates a special Response:
Deferred Data
For streaming SSR, you can defer slow data:<Await>:
Type Safety
React Router provides full type inference:Best Practices
- Keep loaders focused - Each loader should fetch data for its route
- Use actions for mutations - Keep side effects in actions, not loaders
- Return semantic HTTP responses - Use proper status codes (404, 500, etc.)
- Leverage parallel loading - Structure routes to load data in parallel
- Handle errors gracefully - Throw responses to trigger error boundaries
- Use redirect after mutations - Follow the Post/Redirect/Get pattern
- Validate in actions - Return validation errors instead of throwing
- Revalidate wisely - Use
shouldRevalidateto optimize unnecessary loads