Next.js Discord

Discord Forum

Hydration error

Answered
Iridescent shark posted this in #help-forum
Open in Discord
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 });
View full answer

8 Replies

Answer
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
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