-
Notifications
You must be signed in to change notification settings - Fork 487
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error: useMediaQuery is a client-only hook #218
Comments
You're getting this because "use client"
import { useIsClient } from "@uidotdev/usehooks"
export function SomeComponent () {
const isClient = useIsClient()
if (isClient === false) {
return null
}
return <ComponentThatUsesUseDeviceInputType />
} This should also allow you to get rid of the |
If you found this looking for an answer, you can use this component:
"use client";
/**
* Hack to work around next.js hydration
* @see https://github.com/uidotdev/usehooks/issues/218
*/
import React from 'react';
import { useIsClient } from "@uidotdev/usehooks"
type ClientOnlyProps = {
children: React.ReactNode;
};
export const ClientOnly: React.FC<ClientOnlyProps> = ({ children }) => {
const isClient = useIsClient();
// Render children if on client side, otherwise return null
return isClient ? <>{children}</> : null;
}; Then wrap your client components: <ClientOnly>
<MyComponentThatUsesHooks />
</ClientOnly> |
Would this work? import type { useMediaQuery } from "@uidotdev/usehooks";
import dynamic from "next/dynamic";
const useMediaQueryClient = dynamic(
() =>
import("@uidotdev/usehooks").then((module) => {
return module.useMediaQuery;
}),
{
ssr: false,
}
) as typeof useMediaQuery;
export default useMediaQueryClient; |
@tylermcginnis I understand what you say in #218 (comment) is correct. But what I'm not able to understand is, is this – why, if I want to want to use |
What is the proper way to use
useMediaQuery
in a Next.js site? I thought adding a check for window presence and providing defaults would help, but the Error: useMediaQuery is a client-only hook is still thrown from the useMediaQuery hook, where it runs thegetServerSnapshot
.The text was updated successfully, but these errors were encountered: