Skip to main content
The useRoute() hook provides the route() function for React components, enabling URL generation from Laravel route names with automatic configuration handling.

Hook Signature

Parameters

Config
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 Ziggy variable is defined
  • No #ziggy-routes-json script tag exists
  • Running in a non-browser environment (SSR, tests)
Properties:
  • url: Application URL
  • port: Application port (or null)
  • defaults: Default parameter values
  • routes: Route definitions object
  • location: Override current location (for SSR)

Return Value

Returns a configured route() function that can be called with:
  • (name, params?, absolute?, config?) to generate a URL string
  • () with no arguments to return a Router instance
The returned function signature:

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

The useRoute() hook throws an error if no configuration is available:
To prevent errors, always provide configuration when no global Ziggy variable exists:

Server-Side Rendering (SSR)

For SSR with frameworks like Next.js or Remix, provide configuration with a custom location:

Next.js App Router

Next.js Pages Router

TypeScript Support

The hook is fully typed for TypeScript:
With custom configuration:

Implementation Details

The useRoute() hook performs configuration validation and returns a configured route function:
The hook:
  1. Validates that configuration is available from at least one source
  2. Returns a closure that wraps the route() function
  3. Uses defaultConfig as the fallback for the config parameter

Configuration Precedence

Configuration is used in this order (highest to lowest priority):
  1. Per-call config: route('posts.show', 1, true, customConfig)
  2. Hook config: useRoute(defaultConfig)
  3. Global Ziggy variable: window.Ziggy or globalThis.Ziggy
  4. Script tag: <script id="ziggy-routes-json">...</script>

Best Practices

Extract to Custom Hook

Context Provider Pattern

See Also