useMediaQuery
Check if the media query matches the current viewport
The current viewport is mobile
Installation
Usage
Details
Server-Side Rendering (SSR) and Client-Side Behavior
- The hook uses an isomorphic approach to handle both SSR and CSR (client-side rendering). When rendering on the server,
useMediaQueryuses a default value (falseby default) becausewindow.matchMediais not available during SSR. - On the client, the hook utilizes
window.matchMediato accurately determine whether the provided media query matches the current viewport. - The
initializeWithValueoption allows you to control whether the initial render on the client uses the actual match status or a fallback default value, which can help avoid UI mismatches between SSR and CSR.
Media Query Listener
- The hook listens for changes to the viewport that affect the provided media query. Whenever the viewport crosses the query threshold (e.g., resizing from mobile to desktop), the hook updates the
matchesstate accordingly. - It supports Safari < 14 compatibility by using both
addListener/removeListener(deprecated) andaddEventListener/removeEventListenerfor media query events.
Default Value and Initialization
defaultValue: This is primarily useful for SSR. Sincewindow.matchMediais not available on the server, the hook returns this default value during the server-side rendering phase.- Example: You may set
defaultValuetotrueif you want the server-rendered version to assume a "mobile-first" approach when the screen size is unknown.
- Example: You may set
initializeWithValue: This flag controls whether the hook immediately checks the current media query match on the first render. If set tofalse, it skips this check and usesdefaultValueuntil the next effect cycle.
Return Value
- The hook returns a simple boolean (
trueorfalse) indicating whether the media query matches the current viewport. This value can be directly used to conditionally render elements or apply logic in the component.
