useRoute() hook provides the route() function for React components, enabling URL generation from Laravel route names with automatic configuration handling.
Hook Signature
Parameters
Optional Ziggy configuration object to use as the default for all route calls. If not provided, the hook will attempt to use the global
Ziggy variable or load config from a #ziggy-routes-json script tag.Required if:- No global
Ziggyvariable is defined - No
#ziggy-routes-jsonscript tag exists - Running in a non-browser environment (SSR, tests)
url: Application URLport: Application port (ornull)defaults: Default parameter valuesroutes: Route definitions objectlocation: Override current location (for SSR)
Return Value
Returns a configuredroute() function that can be called with:
(name, params?, absolute?, config?)to generate a URL string()with no arguments to return a Router instance
Basic Usage
Usage with Parameters
Usage with Custom Configuration
Advanced Examples
Multiple Parameters
Query Parameters
Relative URLs
Current Route Checking
Route Existence Check
Accessing Current Route Parameters
Error Handling
TheuseRoute() hook throws an error if no configuration is available:
Ziggy variable exists:
Server-Side Rendering (SSR)
For SSR with frameworks like Next.js or Remix, provide configuration with a customlocation:
Next.js App Router
Next.js Pages Router
TypeScript Support
The hook is fully typed for TypeScript:Implementation Details
TheuseRoute() hook performs configuration validation and returns a configured route function:
- Validates that configuration is available from at least one source
- Returns a closure that wraps the
route()function - Uses
defaultConfigas the fallback for theconfigparameter
Configuration Precedence
Configuration is used in this order (highest to lowest priority):- Per-call config:
route('posts.show', 1, true, customConfig) - Hook config:
useRoute(defaultConfig) - Global
Ziggyvariable:window.ZiggyorglobalThis.Ziggy - Script tag:
<script id="ziggy-routes-json">...</script>
Best Practices
Extract to Custom Hook
Context Provider Pattern
See Also
- route() Function - Core route helper
- Router Class - Advanced routing features
- Vue Plugin - Using Ziggy in Vue