`usePathname()` causes hydration error using `pages`
Answered
Yellowhead catfish posted this in #help-forum
Yellowhead catfishOP
import { usePathname } from "next/navigation";
const pathname = usePathname();
<h1 className="text-base font-bold text-neutral-300 group-hover:text-white duration-150">
korino{pathname}
</h1>18 Replies
Yellowhead catfishOP
like it works but its sitll a hydration error even though it displays
Western paper wasp
Maybe it’s just because it’s the 404 page?
Answer
Yellowhead catfishOP
it happens on every page
Western paper wasp
weird
Yellowhead catfishOP
if i like switch from /bot to /pvp it will for some reason display that
but if i just click X on the error prompt thingy it displays the correct path name
Western paper wasp
yeah but the error will still come up in prod unfort
Yellowhead catfishOP
wait
damn i feel dumb
/pvp doesnt exist yet i forgot it just redirects to 404
thats why lmao
Western paper wasp
haha
that would do it
Yellowhead catfishOP
since it just displays the 404 page but the url is still /pvp
Western paper wasp
yeah
Yellowhead catfishOP
yeah that makes sense now lmao
Western paper wasp
If you want to display the pathname on the 404 page, you could always do like a:
so that the pathname doesn’t display until after hydration; that way there won’t be a mismatch
'use client';
import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
const pathname = usePathname();
export default function NotFoundPage() {
const [mounted, setMounted] = useState(false);
useEffect(() => { setMounted(true); }, []);
return (
<h1>
Page not found: {mounted ? pathname : ''}
</h1>
);
}so that the pathname doesn’t display until after hydration; that way there won’t be a mismatch