Hooks
/ API Reference
Hooks
/ API Reference

useRouteChange

A hook that calls a callback when a link is clicked or the pathname changes.

The Gist

'use client'
import { useRouteChange } from '@weser/hooks'

function Component() {
  useRouteChange(() => console.log('route changed'))
}

Parameters

ParameterTypeDescription
callback() => voidThe callback to call when the route changes.
pathnamestring?An optional pathname to listen for.
dependenciesArray<any>?The dependencies passed to useEffect (new tab).

Usage with Frameworks

Most full-stack frameworks provide a way to get the current pathname.
This can be passed as the second parameter to the hook to ensure that programmatic route changes trigger the callback as well.

Here's an example how this looks like in Next.js (new tab):

'use client'
import { usePathname } from 'next/navigation'

function Component() {
  const pathname = usePathname()

  useRouteChange(() => console.log('route changed'), pathname)
}
On this page