Client Functions
React Start provides utilities for working with server functions from the client and for defining client-only code.useServerFn
TheuseServerFn hook wraps a server function for use in React components, providing automatic redirect handling and router integration.
Basic Usage
Why Use useServerFn?
While you can call server functions directly from components,useServerFn provides important benefits:
- Automatic Redirect Handling: Redirects thrown from server functions are automatically handled by the router
- Router Integration: Maintains
_fromLocationfor proper navigation context - Error Propagation: Correctly propagates non-redirect errors
Direct Server Function Calls
You can call server functions directly withoutuseServerFn, but you lose automatic redirect handling:
Custom Fetch Options
Pass custom options when calling server functions:Client-Only Code
Mark modules that should never run on the server:Import Protection
If a server-side file tries to import a client-only module, you’ll get a build error:Mutations with React Query
Combine server functions with React Query for powerful data mutation patterns:Form Handling
Progressive Enhancement
Build forms that work without JavaScript:Optimistic Updates
Update the UI immediately, then reconcile with the server:Error Handling
Handle errors from server functions:Polling and Refetching
Periodically call server functions:Abort Signals
Cancel in-flight requests:Best Practices
Use Transitions for Mutations
Wrap mutations inuseTransition for better UX:
Combine with Suspense
Use Suspense boundaries for loading states:Handle Loading States
Provide feedback during async operations:API Reference
useServerFn(serverFn)
Wraps a server function for use in React components. Parameters:serverFn: Server function created withcreateServerFn
Server Function Call Options
When calling server functions from the client:Related
- Server Functions - Creating server functions
- Components - React Start components
- Middleware - Request and function middleware