diff --git a/.changeset/use-media-shared-cache.md b/.changeset/use-media-shared-cache.md new file mode 100644 index 00000000000..28846cf6e4a --- /dev/null +++ b/.changeset/use-media-shared-cache.md @@ -0,0 +1,5 @@ +--- +'@primer/react': patch +--- + +`useMedia`: share one `MediaQueryList` and one `change` listener per distinct media query instead of allocating a new list and listener for every hook instance. diff --git a/packages/react/src/hooks/__tests__/useMedia.test.tsx b/packages/react/src/hooks/__tests__/useMedia.test.tsx index 729ef97fc46..ce3aba7af7c 100644 --- a/packages/react/src/hooks/__tests__/useMedia.test.tsx +++ b/packages/react/src/hooks/__tests__/useMedia.test.tsx @@ -1,4 +1,5 @@ -import {act, render} from '@testing-library/react' +import {act, render, screen} from '@testing-library/react' +import {Suspense} from 'react' import {afterEach, describe, expect, it, vi} from 'vitest' import ReactDOM from 'react-dom/server' import {useMedia, MatchMedia} from '../useMedia' @@ -14,17 +15,19 @@ function mockMatchMedia({defaultMatch = false} = {}) { Object.defineProperty(window, 'matchMedia', { writable: true, value: vi.fn().mockImplementation(query => ({ - matches: currentMatches, + get matches() { + return currentMatches + }, media: query, onchange: null, addListener: vi.fn(), // deprecated removeListener: vi.fn(), // deprecated - addEventListener: (_type: string, listener: MediaQueryEventListener) => { + addEventListener: vi.fn((_type: string, listener: MediaQueryEventListener) => { listeners.add(listener) - }, - removeEventListener: (_type: string, listener: MediaQueryEventListener) => { + }), + removeEventListener: vi.fn((_type: string, listener: MediaQueryEventListener) => { listeners.delete(listener) - }, + }), dispatchEvent: vi.fn(), })), }) @@ -122,6 +125,106 @@ describe('useMedia', () => { expect(match[1]).toBe(true) }) + it('reads the current match state when a suspended subscriber first mounts', async () => { + const {change} = mockMatchMedia({defaultMatch: true}) + const {promise, resolve} = Promise.withResolvers() + let ready = false + + function TestComponent() { + const matches = useMedia('(min-width: 800px)') + if (!ready) throw promise + return {matches ? 'Wide' : 'Narrow'} + } + + render( + Loading}> + + , + ) + expect(screen.getByText('Loading')).toBeInTheDocument() + + await act(async () => { + change({matches: false}) + ready = true + resolve() + await promise + }) + + expect(screen.getByText('Narrow')).toBeInTheDocument() + expect(window.matchMedia).toHaveBeenCalledTimes(1) + }) + + it('shares one MediaQueryList and one change listener across subscribers of the same query', () => { + const {change} = mockMatchMedia() + + const match: boolean[] = [] + + function TestComponent() { + const value = useMedia('(pointer: coarse)') + match.push(value) + return null + } + + const {unmount} = render( + <> + + + , + ) + + const matchMediaMock = window.matchMedia as unknown as ReturnType + // Both subscribers share a single `matchMedia` call for the query. + expect(matchMediaMock).toHaveBeenCalledTimes(1) + expect(matchMediaMock).toHaveBeenCalledWith('(pointer: coarse)') + + // And a single `change` listener on that shared list. + const sharedList = matchMediaMock.mock.results[0].value as { + addEventListener: ReturnType + removeEventListener: ReturnType + } + expect(sharedList.addEventListener).toHaveBeenCalledTimes(1) + + // A change still reaches every subscriber. + act(() => { + change({matches: true}) + }) + expect(match).toContain(true) + + // Unmounting the last subscriber detaches the listener and drops the entry, + // so the next mount allocates a fresh list. + unmount() + expect(sharedList.removeEventListener).toHaveBeenCalledTimes(1) + + render() + expect(matchMediaMock).toHaveBeenCalledTimes(2) + }) + + it('keeps a separate MediaQueryList per distinct query', () => { + mockMatchMedia() + + function CoarseComponent() { + useMedia('(pointer: coarse)') + return null + } + + function FineComponent() { + useMedia('(pointer: fine)') + return null + } + + render( + <> + + + , + ) + + const matchMediaMock = window.matchMedia as unknown as ReturnType + expect(matchMediaMock).toHaveBeenCalledTimes(2) + expect(matchMediaMock).toHaveBeenCalledWith('(pointer: coarse)') + expect(matchMediaMock).toHaveBeenCalledWith('(pointer: fine)') + }) + it('should default to the features value in context if available', () => { mockMatchMedia() diff --git a/packages/react/src/hooks/useMedia.ts b/packages/react/src/hooks/useMedia.ts index abe36d44ced..4165fead048 100644 --- a/packages/react/src/hooks/useMedia.ts +++ b/packages/react/src/hooks/useMedia.ts @@ -2,6 +2,105 @@ import {useCallback, useContext, useSyncExternalStore} from 'react' import {warning} from '../utils/warning' import {MatchMediaContext} from './MatchMediaContext' +/** + * One shared subscription per distinct media query string. + * + * `window.matchMedia` returns a new `MediaQueryList` on every call, so + * without sharing, every `useMedia` instance allocates its own list and + * registers its own `change` listener (for example, one closed `ActionMenu` + * held 9 live listeners across 3 distinct queries). Sharing one list and one + * listener per query keeps that cost flat however many components subscribe. + */ +type SharedMediaQuery = { + /** The `matchMedia` implementation that produced `mediaQueryList`. */ + matchMediaFn: (query: string) => MediaQueryList + mediaQueryList: MediaQueryList + /** Subscriber callbacks, with a count per callback so repeated + * subscribe/unsubscribe pairs (for example, StrictMode double effects) + * stay balanced. */ + listeners: Map<() => void, number> + /** Shared `change` handler attached to `mediaQueryList`, if any. */ + handleChange: ((event: MediaQueryListEvent) => void) | null + listening: boolean +} + +const sharedMediaQueries = new Map() + +function attachSharedListener(entry: SharedMediaQuery) { + if (entry.listening || !entry.handleChange) { + return + } + // Support fallback to `addListener` for broader browser support + // @ts-ignore this is not present in Safari <14 + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (entry.mediaQueryList.addEventListener) { + entry.mediaQueryList.addEventListener('change', entry.handleChange) + } else { + entry.mediaQueryList.addListener(entry.handleChange) + } + entry.listening = true +} + +function detachSharedListener(entry: SharedMediaQuery) { + if (!entry.listening || !entry.handleChange) { + return + } + // @ts-ignore this is not present in Safari <14 + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (entry.mediaQueryList.removeEventListener) { + entry.mediaQueryList.removeEventListener('change', entry.handleChange) + } else { + entry.mediaQueryList.removeListener(entry.handleChange) + } + entry.listening = false +} + +function createSharedMediaQuery(mediaQueryString: string): SharedMediaQuery { + const mediaQueryList = window.matchMedia(mediaQueryString) + const entry: SharedMediaQuery = { + matchMediaFn: window.matchMedia, + mediaQueryList, + listeners: new Map(), + handleChange: null, + listening: false, + } + entry.handleChange = () => { + for (const listener of entry.listeners.keys()) { + listener() + } + } + return entry +} + +function getSharedMediaQuery(mediaQueryString: string): SharedMediaQuery | undefined { + if (typeof window === 'undefined') { + return undefined + } + + const existing = sharedMediaQueries.get(mediaQueryString) + if (existing) { + if (existing.matchMediaFn === window.matchMedia) { + return existing + } + // The `matchMedia` implementation was replaced (for example, by a test + // mock) so the cached list is stale. Rebuild the entry, carrying any live + // subscribers over to the new list. + const listeners = existing.listeners + detachSharedListener(existing) + const fresh = createSharedMediaQuery(mediaQueryString) + fresh.listeners = listeners + sharedMediaQueries.set(mediaQueryString, fresh) + if (fresh.listeners.size > 0) { + attachSharedListener(fresh) + } + return fresh + } + + const entry = createSharedMediaQuery(mediaQueryString) + sharedMediaQueries.set(mediaQueryString, entry) + return entry +} + /** * `useMedia` will use the given `mediaQueryString` with `matchMedia` to * determine if the document matches the media query string. @@ -27,21 +126,32 @@ export function useMedia(mediaQueryString: string, defaultState?: boolean) { return () => {} } - const mediaQueryList = window.matchMedia(mediaQueryString) + const entry = getSharedMediaQuery(mediaQueryString) + if (!entry) { + return () => {} + } - // Support fallback to `addListener` for broader browser support - // @ts-ignore this is not present in Safari <14 - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (mediaQueryList.addEventListener) { - mediaQueryList.addEventListener('change', onStoreChange) - return () => { - mediaQueryList.removeEventListener('change', onStoreChange) - } + const count = entry.listeners.get(onStoreChange) ?? 0 + entry.listeners.set(onStoreChange, count + 1) + if (entry.listeners.size === 1) { + attachSharedListener(entry) } - mediaQueryList.addListener(onStoreChange) return () => { - mediaQueryList.removeListener(onStoreChange) + const remaining = (entry.listeners.get(onStoreChange) ?? 1) - 1 + if (remaining <= 0) { + entry.listeners.delete(onStoreChange) + } else { + entry.listeners.set(onStoreChange, remaining) + } + if (entry.listeners.size === 0) { + detachSharedListener(entry) + // Only drop the entry if it is still the cached one for this query; + // a `matchMedia` replacement may have swapped in a fresh entry. + if (sharedMediaQueries.get(mediaQueryString) === entry) { + sharedMediaQueries.delete(mediaQueryString) + } + } } }, [contextValue, mediaQueryString], @@ -51,7 +161,8 @@ export function useMedia(mediaQueryString: string, defaultState?: boolean) { if (contextValue !== undefined) { return contextValue } - return window.matchMedia(mediaQueryString).matches + // Read the live list even when its first subscriber has not mounted yet. + return getSharedMediaQuery(mediaQueryString)?.mediaQueryList.matches ?? false }, [contextValue, mediaQueryString]) const getServerSnapshot = useCallback(() => {