Repository navigation
Conversation
Closes primer#8720 Each useMedia instance called window.matchMedia on every render and registered its own change listener, so one closed ActionMenu held 9 live listeners across 3 distinct queries. Keep a module-level cache of one MediaQueryList plus one shared change listener per query string, with reference-counted subscribers; the cached match state is updated from the change event, and the entry is dropped when the last subscriber unmounts.
🦋 Changeset detectedLatest commit: f87ef07 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
llastflowers
left a comment
There was a problem hiding this comment.
Could we read the cached MediaQueryList.matches directly here? If a component suspends and the viewport changes before it subscribes, the cached boolean stays stale. I reproduced this by resizing from 1000px to 500px while suspended—the hook still returned true for (min-width: 800px) after loading. A regression test for that case would be helpful too.
|
|
Closes #8720
Changelog
New
None.
Changed
useMedianow shares oneMediaQueryListand onechangelistener per distinct media query string instead of allocating a new list and registering a new listener for every hook instance. The cached match state is updated from thechangeevent, and the entry is dropped (listener detached) when the last subscriber unmounts.matchMediacall and a singlechangelistener, different queries keep separate lists, and unmounting the last subscriber detaches the listener so the next mount allocates a fresh list.Removed
None.
Rollout strategy
Testing & Reviewing
npx vitest run packages/react/src/hooks/__tests__/useMedia.test.tsx packages/react/src/hooks/__tests__/useResponsiveValue.test.tsx: 12 passed (7 useMedia, including the 2 new sharing tests, and 5 useResponsiveValue).npx eslint packages/react/src/hooks/useMedia.ts packages/react/src/hooks/__tests__/useMedia.test.tsx: clean.npx tsc --noEmitinpackages/react: 17 errors, all pre-existing on unmodifiedmain(duplicate@babel/typesand missing@primer/doc-genbuild artifacts in this environment); none in the changed files.Notes for reviewers:
useResponsiveValuehalf of useMedia, useResponsiveValue: share MediaQueryList instances and listeners #8720 (skipping its threeuseMediacalls for non-responsive values): hooks cannot be called conditionally, so that would need a restructure of the hook rather than this sharing change. Happy to follow up separately if maintainers want it.matchMediaimplementation that created it, so replacingmatchMedia(for example, a test mock) rebuilds the entry and carries live subscribers over, instead of serving a stale list.