Next.js Discord

Discord Forum

Router events example

Answered
Silver carp posted this in #help-forum
Open in Discord
Silver carpOP
In the official website example, it made it as an component to be imported in layout.
Is there any reason that it has to be a component?
I think composing usePathname and useSearchParams as a custom hook is sufficient.

useNavigationEvents.js

'use client'
 
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
 
const useNavigationEvent = () => {
  const pathname = usePathname()
  const searchParams = useSearchParams()
 
  useEffect(() => {
    const url = `${pathname}?${searchParams}`
    console.log(url)
    // You can now use the current URL
    // ...
  }, [pathname, searchParams])
}



official website example
app/components/navigation-events.js
'use client'
 
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
 
export function NavigationEvents() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
 
  useEffect(() => {
    const url = `${pathname}?${searchParams}`
    console.log(url)
    // You can now use the current URL
    // ...
  }, [pathname, searchParams])
 
  return null
}
Answered by James4u
well @Silver carp I think that's because in app router, a server component can include client components but if you create it as a hook you can't use it in server component
View full answer

11 Replies

Silver carpOP
bump
well @Silver carp I think that's because in app router, a server component can include client components but if you create it as a hook you can't use it in server component
Answer
@necm1 was writing this 😭
am very fast at typing
8+
@James4u am very fast at typing
its 04:51 AM :crythumbsupcat:
Silver carpOP
@necm1 Thank you as well
@Silver carp <@315806345376825344> Thank you as well
you're welcome and dont feel bad