uidotdev / usehooks

A collection of modern, server-safe React hooks – from the ui.dev team

Home Page:https://usehooks.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useMediaQuery causes error when used with Nextjs (not server safe)

ottovw opened this issue · comments

useMediaQuery causes errors when using with Nextjs (13.4.19, App Router)

It "works", but the console is full of errors.

- error node_modules/@uidotdev/usehooks/index.js (803:0) @ getServerSnapshot
- error Error: useMediaQuery is a client-only hook
    at useIsSmall (./components/hooks/use-is-small.ts:8:77)
    at DynamicHeader (./components/layout/dynamic-header.tsx:31:72)
null

DynamicHeader is a 'use client' component.

Most likely due to the server snapshot, but I thought this should be "server safe"

Here's a possible solution:

export function useMediaQuery(query: string, defaultSSRValue = false) {
    const subscribe = useCallback(
        (callback: any) => {
            const matchMedia = window.matchMedia(query);

            matchMedia.addEventListener("change", callback);
            return () => {
                matchMedia.removeEventListener("change", callback);
            };
        },
        [query]
    );

    const getSnapshot = () => {
        return window.matchMedia(query).matches;
    };

    const getServerSnapshot = () => {
        return defaultSSRValue
    };

    return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}