Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(hooks): rewrite useMediaQuery with useSyncExternalStore (#2272)

Andrey Goder0004b90d096c
diff --git a/packages/core/src/AppShell/XDSAppShell.test.tsx b/packages/core/src/AppShell/XDSAppShell.test.tsx
index 857e8a760e..e90af250c9 100644
--- a/packages/core/src/AppShell/XDSAppShell.test.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.test.tsx
@@ -251,14 +251,19 @@ describe('XDSAppShell', () => {
expect(window.matchMedia).toHaveBeenCalled();
});
- it('does not track breakpoint when mobileNav breakpoint is none', () => {
+ it('does not enter mobile mode when mobileNav breakpoint is none', () => {
render(
<XDSAppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'none'}}>
<div>Content</div>
</XDSAppShell>,
);
- expect(window.matchMedia).not.toHaveBeenCalled();
+ // breakpoint 'none' uses (max-width: 0px) which never matches,
+ // so sideNav stays inline and no mobile nav toggle appears
+ expect(screen.getByText('Nav')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: /menu/i}),
+ ).not.toBeInTheDocument();
});
// ===========================================================================
diff --git a/packages/core/src/AppShell/XDSAppShell.tsx b/packages/core/src/AppShell/XDSAppShell.tsx
index b94c644ab1..3347315311 100644
--- a/packages/core/src/AppShell/XDSAppShell.tsx
+++ b/packages/core/src/AppShell/XDSAppShell.tsx
@@ -51,6 +51,7 @@ import type {XDSAppShellMobileContextValue} from './XDSAppShellMobileContext';
import type {SpacingStep} from '../utils/types';
import type {XDSBaseProps} from '../XDSBaseProps';
import {xdsClassName, mergeProps} from '../utils';
+import {useMediaQuery} from '../hooks/useMediaQuery';
import {observeResize, unobserveResize} from '../utils/sharedResizeObserver';
const HasActivity = typeof React.Activity !== 'undefined';
@@ -470,7 +471,6 @@ export function XDSAppShell({
const mobileNavConfigContent: ReactNode | null =
mobileNavConfig?.content ?? null;
const mobileNavHasToggle = mobileNavConfig?.hasToggle !== false;
- const mobileNavDefaultIsMobile = mobileNavConfig?.defaultIsMobile ?? false;
const mobileNavIsControlled = mobileNavConfig?.isOpen !== undefined;
// =========================================================================
@@ -488,9 +488,11 @@ export function XDSAppShell({
// =========================================================================
// Mobile nav open state (controlled + uncontrolled)
// =========================================================================
- const [isBelowBreakpoint, setIsBelowBreakpoint] = useState(
- mobileNavDefaultIsMobile,
- );
+ const breakpointQuery =
+ sideNavBreakpoint === 'none'
+ ? '(max-width: 0px)'
+ : `(max-width: ${BREAKPOINT_VALUES[sideNavBreakpoint]}px)`;
+ const isBelowBreakpoint = useMediaQuery(breakpointQuery);
const [uncontrolledMobileOpen, setUncontrolledMobileOpen] = useState(false);
const isMobileNavOpen = mobileNavConfig?.isOpen ?? uncontrolledMobileOpen;
@@ -574,33 +576,6 @@ export function XDSAppShell({
return () => unobserveResize(headerEl);
}, [isAuto]);
- // =========================================================================
- // Responsive breakpoint handling
- //
- // Uses matchMedia which is event-driven — the listener only fires when the
- // media query match state actually changes, not on every resize. This is
- // efficient and does not over-trigger.
- // =========================================================================
- useEffect(() => {
- if (sideNavBreakpoint === 'none') {
- return;
- }
-
- const breakpointPx = BREAKPOINT_VALUES[sideNavBreakpoint];
- const mql = window.matchMedia(`(max-width: ${breakpointPx}px)`);
-
- const handleChange = (e: MediaQueryListEvent | MediaQueryList) => {
- const matches = 'matches' in e ? e.matches : false;
- setIsBelowBreakpoint(matches);
- };
-
- // Check initial state
- handleChange(mql);
-
- mql.addEventListener('change', handleChange);
- return () => mql.removeEventListener('change', handleChange);
- }, [sideNavBreakpoint]);
-
// =========================================================================
// Determine if sideNav should show as overlay (mobile) or inline
// =========================================================================
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
index 5fe375840a..992983315c 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
@@ -46,12 +46,15 @@ beforeAll(() => {
Object.defineProperty(event, 'newState', {value: 'closed'});
this.dispatchEvent(event);
});
- HTMLElement.prototype.matches = function (selector: string) {
+ HTMLElement.prototype.matches = function (
+ this: HTMLElement,
+ selector: string,
+ ) {
if (selector === ':popover-open') {
return popoverOpenState.get(this) ?? false;
}
return originalMatches.call(this, selector);
- };
+ } as typeof HTMLElement.prototype.matches;
});
beforeEach(() => {
diff --git a/packages/core/src/hooks/useMediaQuery.test.ts b/packages/core/src/hooks/useMediaQuery.test.ts
index 405d8248f8..6b24a3f989 100644
--- a/packages/core/src/hooks/useMediaQuery.test.ts
+++ b/packages/core/src/hooks/useMediaQuery.test.ts
@@ -51,18 +51,16 @@ describe('useMediaQuery', () => {
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
});
- it('returns false on initial render (SSR-safe)', () => {
+ it('returns false when media query does not match', () => {
const {result} = renderHook(() => useMediaQuery('(max-width: 768px)'));
- // Before the effect runs, should be false
expect(result.current).toBe(false);
});
- it('syncs with matchMedia on mount', () => {
+ it('returns true when media query matches', () => {
mockMql = createMockMatchMedia(true);
vi.stubGlobal('matchMedia', vi.fn().mockReturnValue(mockMql));
const {result} = renderHook(() => useMediaQuery('(max-width: 768px)'));
- // After effect, should match the mql state
expect(result.current).toBe(true);
});
diff --git a/packages/core/src/hooks/useMediaQuery.ts b/packages/core/src/hooks/useMediaQuery.ts
index 298756a05d..83060dd210 100644
--- a/packages/core/src/hooks/useMediaQuery.ts
+++ b/packages/core/src/hooks/useMediaQuery.ts
@@ -4,39 +4,47 @@
/**
* @file useMediaQuery.ts
- * @input Uses React useState, useEffect
+ * @input Uses React useSyncExternalStore, useCallback
* @output Exports useMediaQuery hook for responsive breakpoint detection
* @position Core hook; used by consumers for responsive patterns
*
- * SSR-safe media query hook that subscribes to window.matchMedia changes.
+ * SSR-safe media query hook that subscribes to window.matchMedia changes
+ * via useSyncExternalStore — the canonical React pattern for external
+ * browser state.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
*/
+import {useCallback, useSyncExternalStore} from 'react';
-import {useState, useEffect} from 'react';
+function getServerSnapshot(): boolean {
+ return false;
+}
/**
* SSR-safe media query hook.
* Returns whether the given media query matches.
*
* @example
- * ```tsx
+ * ```
* const isMobile = useMediaQuery('(max-width: 768px)');
* const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
* ```
*/
export function useMediaQuery(query: string): boolean {
- const [matches, setMatches] = useState(false); // Always false on first render (SSR-safe)
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => {
+ const mql = window.matchMedia(query);
+ mql.addEventListener('change', onStoreChange);
+ return () => mql.removeEventListener('change', onStoreChange);
+ },
+ [query],
+ );
- useEffect(() => {
- const mql = window.matchMedia(query);
- setMatches(mql.matches); // Sync on mount
- const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
- mql.addEventListener('change', handler);
- return () => mql.removeEventListener('change', handler);
+ const getSnapshot = useCallback(() => {
+ return window.matchMedia(query).matches;
}, [query]);
- return matches;
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}