Next.js Discord

Discord Forum

useEffect is not being called when I navigate using Link

Answered
American Bobtail posted this in #help-forum
Open in Discord
American BobtailOP
I'm facing this issue of that when I enter the url manually the code works fine and it redirects, but if I navigated to the page using <Link /> the useEffect is not triggered at all

const pathname =
typeof window !== 'undefined' ? window.location.pathname : '';

useEffect(() => {
const handleRedirects = () => {
if (
!token &&
authorizedPrefix.some((prefix) => pathname.startsWith(prefix))
) {
router.push('/login');
} else if (
token &&
unauthorizedPrefix.some((prefix) => pathname.startsWith(prefix))
) {
router.push('/dashboard');
}
};
handleRedirects();
}, [token, pathname, router]);

This piece of code is in layout.js under /src/app
Answered by Arinji
Try out usePathname, it will cause your layout to rerender, also if you just want the layout to update on linking, you can use a template.tsx file, it's like layouts but will rerender automatically
View full answer

4 Replies

@American Bobtail ok so a lot of stuff happens in your code
So basically layouts won't rerender normally when linking, this shld idea be fine since you put the pathname as a deps array, but the way you are getting the pathname makes it so it won't update.
Try out usePathname, it will cause your layout to rerender, also if you just want the layout to update on linking, you can use a template.tsx file, it's like layouts but will rerender automatically
Answer
American BobtailOP
@Arinji Oh I see, I didn't know about such a hook. Thank you it's working now! I'll also check the template file way