Utilities
useMediaQuery
A primitive that tracks whether a CSS media query matches.
useMediaQuery returns an accessor that tells whether a media query matches, and updates when it
starts or stops matching. Resize the window or change your system's color scheme to see the demo
update.
(min-width: 768px)no match(prefers-color-scheme: dark)no match(prefers-reduced-motion: reduce)no match(hover: hover)no match
Usage#
import { useMediaQuery } from '@egoist/solid-base/unstable-use-media-query';
function Navigation() {
const isDesktop = useMediaQuery('(min-width: 768px)');
return (
<Show when={isDesktop()} fallback={<MobileNavigation />}>
<DesktopNavigation />
</Show>
);
}The query can be written with or without the leading @media, and can be an accessor to track a
query that changes:
const [breakpoint, setBreakpoint] = createSignal(768);
const matches = useMediaQuery(() => `(min-width: ${breakpoint()}px)`);Server rendering#
window.matchMedia() is unavailable on the server, so the primitive returns defaultMatches
(false by default) during server rendering and on the client until hydration completes. It then
switches to the real value, which avoids hydration mismatches.
- Set
defaultMatchesto the value most of your users will get. - Provide
ssrMatchMediato compute the server value from the request, for example from the user agent or client hints. - Set
noSsrwhen the value is only used on the client: the real value is then read immediately during hydration instead of after it.
const isDesktop = useMediaQuery('(min-width: 768px)', {
ssrMatchMedia: (query) => ({ matches: guessFromUserAgent(query) }),
});API reference#
function useMediaQuery(
query: string | Accessor<string>,
options?: useMediaQuery.Options,
): Accessor<boolean>;Parameters#
| Parameter | Type | Description |
|---|---|---|
query |
string | Accessor<string> |
The media query, with or without the leading @media. |
options |
useMediaQuery.Options |
Optional. Read lazily, so its properties can be getters. |
Options#
defaultMatchesboolean— The value returned on the server and until hydration completes, aswindow.matchMedia()is unavailable on the server. Defaults tofalse.matchMediatypeof window.matchMedia | null— A custommatchMediaimplementation, for example to match against an iframe's content window. Passnullto disable media query matching.noSsrboolean— Reads the real value immediately during hydration instead of after it. Set it totrueonly if you use the returned value on the client. Defaults tofalse.ssrMatchMedia(query: string) => { matches: boolean }— AmatchMediaimplementation used when rendering on the server (and until hydration completes).
Return value#
| Type | Description |
|---|---|
Accessor<boolean> |
Whether the query currently matches. Updates when it changes. |