useMediaQuery
Check if the media query matches the current viewport
The current viewport is mobile
Installation
Copy-paste the hook
Copy and paste the hook code in a .ts
file.
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,
useMediaQuery
uses a default value (false
by default) becausewindow.matchMedia
is not available during SSR. - On the client, the hook utilizes
window.matchMedia
to accurately determine whether the provided media query matches the current viewport. - The
initializeWithValue
option 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
matches
state accordingly. - It supports Safari < 14 compatibility by using both
addListener
/removeListener
(deprecated) andaddEventListener
/removeEventListener
for media query events.
Default Value and Initialization
defaultValue
: This is primarily useful for SSR. Sincewindow.matchMedia
is not available on the server, the hook returns this default value during the server-side rendering phase.- Example: You may set
defaultValue
totrue
if 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 usesdefaultValue
until the next effect cycle.
Return Value
- The hook returns a simple boolean (
true
orfalse
) 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.