-
Notifications
You must be signed in to change notification settings - Fork 5
feat(useMediaQuery): enhance hook with debounce, fallback and onChange #95
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| # useMediaQuery | ||
|
|
||
| A performant, SSR-safe React hook for tracking media queries using `useSyncExternalStore`. Optimized for Next.js and React 18+ with support for legacy browsers. | ||
|
|
||
| ## Basic Usage | ||
|
|
||
| Perfect for simple responsive logic in client components. | ||
|
|
||
| ```jsx | ||
| import { useMediaQuery } from '@barso/hooks'; | ||
|
|
||
| function SimpleComponent() { | ||
| const isMobile = useMediaQuery('(max-width: 768px)'); | ||
|
|
||
| return <div>{isMobile ? 'Viewing on Mobile' : 'Viewing on Desktop'}</div>; | ||
| } | ||
| ``` | ||
|
|
||
| ## Features | ||
|
|
||
| - ⚡ **React 18 Ready**: Uses `useSyncExternalStore` to prevent "tearing" and ensure consistency. | ||
| - 🌐 **SSR/Next.js Compatible**: Handles hydration gracefully with customizable fallbacks. | ||
| - ⏱️ **Built-in Debounce**: Optional delay to prevent excessive re-renders during window resizing. | ||
| - 🔄 **Legacy Support**: Automatic fallback for browsers not supporting `addEventListener` on `matchMedia`. | ||
| - 🎣 **Event Callback**: Integrated `onChange` listener for side effects. | ||
|
|
||
| ## Advanced Example: Theming with `prefers-color-scheme` | ||
|
|
||
| To prevent **Flash of Unstyled Content (FOUC)** or layout shifts in Next.js, you can sync the server-side state (derived from cookies or user-agent) with the hook using the `fallback` option. | ||
|
|
||
| ```jsx | ||
| // app/page.js (Server Component) | ||
| import { cookies } from 'next/headers'; | ||
| import ThemeWrapper from './ThemeWrapper'; | ||
|
|
||
| export default function Page() { | ||
| // Read the saved theme from cookies to ensure the server renders the correct UI | ||
| const themeCookie = cookies().get('theme')?.value; | ||
| const isDarkMode = themeCookie === 'dark'; | ||
|
|
||
| return <ThemeWrapper initialIsDark={isDarkMode} />; | ||
| } | ||
|
|
||
| // ThemeWrapper.js (Client Component) | ||
| 'use client'; | ||
| import { useMediaQuery } from '@barso/hooks'; | ||
|
|
||
| export default function ThemeWrapper({ initialIsDark }) { | ||
| const isDark = useMediaQuery('(prefers-color-scheme: dark)', { | ||
| // Use the server-provided state during hydration | ||
| fallback: initialIsDark, | ||
| // Optional: add debounce for smoother transitions | ||
| debounceMs: 200, | ||
| onChange: (matches) => { | ||
| console.log('Theme changed to:', matches ? 'dark' : 'light'); | ||
| } | ||
| }); | ||
|
|
||
| return ( | ||
| <div className={isDark ? 'dark-mode' : 'light-mode'}> | ||
| <h1>Themed Content</h1> | ||
| </div> | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| ## API Reference | ||
|
|
||
| ### `useMediaQuery(query, options)` | ||
|
|
||
| | Argument | Type | Description | | ||
| | --------- | -------- | ------------------------------------------------------- | | ||
| | `query` | `string` | The media query to track (e.g., `(min-width: 1024px)`). | | ||
| | `options` | `object` | Configuration object. | | ||
|
|
||
| ### Options | ||
|
|
||
| | Property | Type | Default | Description | | ||
| | ------------ | -------------------------------- | ----------- | -------------------------------------------------- | | ||
| | `debounceMs` | `number` | `undefined` | Delay in ms to wait before updating the state. | | ||
| | `fallback` | `boolean` | `() => boolean` | `false` | Initial value used on server and during hydration. | | ||
| | `onChange` | `(matches: boolean) => void` | `undefined` | Callback function triggered on every change. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,17 +1,74 @@ | ||
| import { useEffect, useState } from 'react'; | ||
| import { noop } from '@barso/helpers'; | ||
| import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react'; | ||
|
|
||
| export function useMediaQuery(query) { | ||
| const [matches, setMatches] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(query)?.matches); | ||
| /** | ||
| * @typedef {Object} UseMediaQueryOptions | ||
| * @property {number} [debounceMs] - Delay in ms before updating the state. | ||
| * @property {boolean | (() => boolean)} [fallback=false] - Initial state used during SSR and hydration. | ||
| * @property {(matches: boolean) => void} [onChange] - Callback fired when the query match state changes. | ||
| */ | ||
|
|
||
| useEffect(() => { | ||
| const media = window.matchMedia(query); | ||
| const listener = () => setMatches(media.matches); | ||
| /** | ||
| * A robust React hook to monitor media queries, optimized for Next.js and React 18+. | ||
| * @param {string} query - The media query string to monitor (e.g., '(max-width: 768px)'). | ||
| * @param {UseMediaQueryOptions} [options] - Optional configuration for debounce, SSR fallback, and change events. | ||
| * @returns {boolean} - Returns true if the media query matches, false otherwise. | ||
| */ | ||
| export function useMediaQuery(query, { debounceMs, fallback = false, onChange } = {}) { | ||
| const getServerSnapshot = () => (typeof fallback === 'function' ? fallback() : fallback); | ||
|
|
||
| listener(); | ||
| const mql = useMemo(() => { | ||
| if (typeof window === 'undefined' || !window.matchMedia) { | ||
| return { matches: getServerSnapshot(), isFallback: true }; | ||
| } | ||
|
|
||
| media.addEventListener('change', listener); | ||
| return () => media.removeEventListener('change', listener); | ||
| return window.matchMedia(query); | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [query]); | ||
|
|
||
| const timeoutRef = useRef(); | ||
|
|
||
| const subscribe = useCallback( | ||
| (notify) => { | ||
| if (mql.isFallback) return noop; | ||
|
|
||
| const handleChange = () => { | ||
| if (!debounceMs) return notify(); | ||
|
|
||
| clearTimeout(timeoutRef.current); | ||
| timeoutRef.current = setTimeout(notify, debounceMs); | ||
| }; | ||
|
|
||
| if (!mql.addEventListener) { | ||
| mql.addListener?.(handleChange); | ||
| return () => { | ||
| mql.removeListener?.(handleChange); | ||
| clearTimeout(timeoutRef.current); | ||
| }; | ||
| } | ||
|
|
||
| mql.addEventListener('change', handleChange); | ||
|
|
||
| return () => { | ||
| mql.removeEventListener('change', handleChange); | ||
| clearTimeout(timeoutRef.current); | ||
| }; | ||
| }, | ||
| [debounceMs, mql], | ||
| ); | ||
|
|
||
| const getSnapshot = () => mql.matches; | ||
|
|
||
| const matches = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); | ||
|
|
||
| const lastValueRef = useRef(matches); | ||
|
|
||
| useEffect(() => { | ||
| if (typeof onChange !== 'function' || matches === lastValueRef.current) return; | ||
|
|
||
| lastValueRef.current = matches; | ||
| onChange(matches); | ||
| }, [matches, onChange]); | ||
|
|
||
| return matches; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.