Skip to main content

useRouter

The useRouter 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

export function useRouter() {
  const navigate = useNavigate()
  const location = useLocation()

  function navigateTo(path) {
    navigate(path)
  }

  return {
    currentPath: location.pathname,
    navigateTo
  }
}

Parameters

This hook takes no parameters.

Return Value

Returns an object with the following properties:
PropertyTypeDescription
currentPathstringCurrent pathname (e.g., /search, /jobs/123)
navigateTofunctionFunction to navigate to a new path

Usage Example

From src/pages/Home.jsx:
import useRouter from "@/hooks/useRouter"

export function HomePage() {
  const { navigateTo } = useRouter()

  const handleSearch = (event) => {
    event.preventDefault()
    const formData = new FormData(event.currentTarget)
    const searchText = formData.get('search')
    const url = searchText 
      ? `/search?text=${encodeURIComponent(searchText)}` 
      : '/search'
    navigateTo(url)
  }

  return (
    <main>
      <form role="search" onSubmit={handleSearch}>
        <input 
          required 
          type="text" 
          placeholder="Buscar empleos por título, habilidad o empresa"
          name="search"
        />
        <button type="submit">Buscar</button>
      </form>
    </main>
  )
}
Navigates to a new path programmatically. Parameters:
  • path (string): Target path, can include query parameters
Examples:
// Navigate to search page
navigateTo('/search')

// Navigate with query parameters
navigateTo('/search?text=react&technology=javascript')

// Navigate to job detail
navigateTo('/jobs/123')

// Navigate with encoded parameters
const searchText = 'frontend developer'
navigateTo(`/search?text=${encodeURIComponent(searchText)}`)

currentPath

The current pathname without query parameters or hash. Examples:
const { currentPath } = useRouter()

// On page: /search?text=react
console.log(currentPath) // "/search"

// On page: /jobs/123
console.log(currentPath) // "/jobs/123"

// Conditional rendering based on path
if (currentPath === '/search') {
  // Show search-specific UI
}

Common Patterns

Form Submission Navigation

Navigate after form submission:
const { navigateTo } = useRouter()

const handleSubmit = (event) => {
  event.preventDefault()
  const formData = new FormData(event.currentTarget)
  const params = new URLSearchParams()
  
  formData.forEach((value, key) => {
    if (value) params.append(key, value)
  })
  
  navigateTo(`/search?${params.toString()}`)
}

Conditional Navigation

Navigate based on application logic:
const { navigateTo } = useRouter()

const handleSearch = (searchText) => {
  if (searchText.trim()) {
    navigateTo(`/search?text=${encodeURIComponent(searchText)}`)
  } else {
    navigateTo('/search')
  }
}

Building URLs with Parameters

const { navigateTo } = useRouter()

const searchWithFilters = (text, filters) => {
  const params = new URLSearchParams()
  
  if (text) params.append('text', text)
  if (filters.technology) params.append('technology', filters.technology)
  if (filters.location) params.append('type', filters.location)
  
  navigateTo(`/search?${params.toString()}`)
}

// Usage
searchWithFilters('react developer', {
  technology: 'react',
  location: 'remoto'
})
// Navigates to: /search?text=react+developer&technology=react&type=remoto

Active Navigation Highlighting

const { currentPath } = useRouter()

function NavLink({ to, children }) {
  const isActive = currentPath === to
  
  return (
    <a 
      href={to}
      className={isActive ? 'active' : ''}
      onClick={(e) => {
        e.preventDefault()
        navigateTo(to)
      }}
    >
      {children}
    </a>
  )
}

When to Use useRouter

Use useRouter 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 useNavigate options (replace, state)
  • Route matching: Use useMatch or useParams for route parameters

Comparison with React Router

useRouter (Simplified)

import useRouter from '@/hooks/useRouter'

const { navigateTo, currentPath } = useRouter()
navigateTo('/search')

React Router (Full API)

import { useNavigate, useLocation } from 'react-router-dom'

const navigate = useNavigate()
const location = useLocation()

navigate('/search', { replace: false, state: { from: 'home' } })
console.log(location.pathname)

Best Practices

1. Always Encode URL Parameters

Use encodeURIComponent for user input:
const searchText = formData.get('search')
const url = `/search?text=${encodeURIComponent(searchText)}`
navigateTo(url)

2. Prevent Default Form Behavior

Prevent full page reloads:
const handleSubmit = (event) => {
  event.preventDefault() // Important!
  navigateTo('/search')
}

3. Handle Empty Values

Only include parameters with values:
const url = searchText 
  ? `/search?text=${encodeURIComponent(searchText)}` 
  : '/search'
navigateTo(url)

4. Use URLSearchParams for Multiple Parameters

const params = new URLSearchParams()
if (text) params.append('text', text)
if (tech) params.append('technology', tech)

navigateTo(`/search?${params.toString()}`)

Implementation Details

The hook is a thin wrapper that:
  1. Exposes location.pathname as currentPath
  2. Wraps navigate() in a named function navigateTo()
  3. Provides a consistent, simple API across the application

Dependencies

  • react-router-dom: useNavigate, useLocation

Build docs developers (and LLMs) love