how to detect route change in next 14
Unanswered
Donskoy posted this in #help-forum
DonskoyOP
How can we detect route change and clear the state on page change in next 14
7 Replies
You can use the
https://nextjs.org/docs/app/api-reference/functions/use-pathname
usePathname() hook from next/navigation.https://nextjs.org/docs/app/api-reference/functions/use-pathname
you can find the example bottom of the page: https://nextjs.org/docs/app/api-reference/functions/use-pathname#do-something-in-response-to-a-route-change
if you want it to be apply in every page, IG you can create a client component wrapper, and use it in layout.tsx. something like this:
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<body className={spaceGrotest.className}>
<Wrapper>
{children}
</Wrapper>
<Toaster />
</body>
</html>
);
}DonskoyOP
that is fine but how can i detect change in my controller and clear the state.
page url is same just the params is different
Use the useSearchParams hook also described on that page in the docs.
Swainson's Thrush
I don't know your use case but if you want to reinitialize your state in
layout on page change try using template instead of layout.