useRouter
TheuseRouter hook is a lightweight wrapper around React Router’s useNavigate and useLocation hooks. It provides a simplified API for programmatic navigation and path tracking.
Location
/src/hooks/useRouter.js
Function Signature
Parameters
This hook takes no parameters.Return Value
Returns an object with the following properties:| Property | Type | Description |
|---|---|---|
currentPath | string | Current pathname (e.g., /search, /jobs/123) |
navigateTo | function | Function to navigate to a new path |
Usage Example
Fromsrc/pages/Home.jsx:
navigateTo(path)
Navigates to a new path programmatically. Parameters:path(string): Target path, can include query parameters
currentPath
The current pathname without query parameters or hash. Examples:Common Patterns
Form Submission Navigation
Navigate after form submission:Conditional Navigation
Navigate based on application logic:Building URLs with Parameters
Active Navigation Highlighting
When to Use useRouter
UseuseRouter when you need:
- Programmatic navigation: Navigate in response to events (form submissions, button clicks)
- Conditional routing: Navigate based on application logic
- URL building: Construct URLs with query parameters dynamically
- Path-based UI: Show/hide UI elements based on current route
When to Use React Router Directly
Use React Router’s components and hooks directly when:- Declarative navigation: Use
<Link>for standard navigation links - Advanced routing: Use
useNavigateoptions (replace, state) - Route matching: Use
useMatchoruseParamsfor route parameters
Comparison with React Router
useRouter (Simplified)
React Router (Full API)
Best Practices
1. Always Encode URL Parameters
UseencodeURIComponent for user input:
2. Prevent Default Form Behavior
Prevent full page reloads:3. Handle Empty Values
Only include parameters with values:4. Use URLSearchParams for Multiple Parameters
Implementation Details
The hook is a thin wrapper that:- Exposes
location.pathnameascurrentPath - Wraps
navigate()in a named functionnavigateTo() - Provides a consistent, simple API across the application
Related Hooks
- useFilters - Uses URL parameters managed by this hook
- useSearchForm - Works with URL synchronization
Dependencies
react-router-dom:useNavigate,useLocation