Hydration error
Answered
Iridescent shark posted this in #help-forum
Iridescent sharkOP
I'm getting hydration error at
{matches ? <LogOut className="w-5 h-5" /> : "Log out"}. How can I fix it?"use client";
import { Button } from "@/components/ui/button";
import { FC } from "react";
import { useMediaQuery } from "usehooks-ts";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { LogIn, LogOut } from "lucide-react";
const Profile: FC = () => {
const matches = useMediaQuery("(max-width: 768px)");
const session = useSession();
if (session.status === "authenticated") {
return (
<Button size={matches ? "icon" : "default"}>
<Link href="/api/auth/signout?callbackUrl=/api/auth/signin">
{matches ? <LogOut className="w-5 h-5" /> : "Log out"}
</Link>
</Button>
);
}
return (
<Button size={matches ? "icon" : "default"}>
<Link href="/api/auth/signin">
{matches ? <LogIn className="w-5 h-5" /> : "Log in"}
</Link>
</Button>
);
};
export default Profile;Answered by joulev
const matches = useMediaQuery("(max-width: 768px)", { initializeWithValue: false });8 Replies
initializeWithValue?boolean
If true (default), the hook will initialize reading the media query. In SSR, you should set it to false, returning options.defaultValue or false initially. Default ts true
– https://usehooks-ts.com/react-hook/use-media-query
@Iridescent shark I'm getting hydration error at `{matches ? <LogOut className="w-5 h-5" /> : "Log out"}`. How can I fix it?
"use client";
import { Button } from "@/components/ui/button";
import { FC } from "react";
import { useMediaQuery } from "usehooks-ts";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { LogIn, LogOut } from "lucide-react";
const Profile: FC = () => {
const matches = useMediaQuery("(max-width: 768px)");
const session = useSession();
if (session.status === "authenticated") {
return (
<Button size={matches ? "icon" : "default"}>
<Link href="/api/auth/signout?callbackUrl=/api/auth/signin">
{matches ? <LogOut className="w-5 h-5" /> : "Log out"}
</Link>
</Button>
);
}
return (
<Button size={matches ? "icon" : "default"}>
<Link href="/api/auth/signin">
{matches ? <LogIn className="w-5 h-5" /> : "Log in"}
</Link>
</Button>
);
};
export default Profile;
Cuvier’s Dwarf Caiman
SignIn is probably a button, and you can’t put a button in another button. So try removing the <Button>
no it's just the hook is not hydration-safe. generally hooks that make use of
window APIs, such as useLocalStorage, useMediaQuery, useIsDarkMode, etc. are mostly not hydration-safe and require special handling. in this case it is possible to make it hydration-safe via initializeWithValue.@B33fb0n3 what's inside LogOut ?
Iridescent sharkOP
LogOut is svg icon from lucide library
And based on media query I want to display icon or text
@joulev `const matches = useMediaQuery("(max-width: 768px)", { initializeWithValue: false });`
Iridescent sharkOP
It worked, thank you