Skip to content

Commit

Permalink
useMatchMedia: cache queries (#61000)
Browse files Browse the repository at this point in the history
Co-authored-by: ellatrix <ellatrix@git.wordpress.org>
Co-authored-by: jsnajdr <jsnajdr@git.wordpress.org>
Co-authored-by: tyxla <tyxla@git.wordpress.org>
  • Loading branch information
4 people authored Apr 23, 2024
1 parent 4ec0363 commit e6c62c8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
17 changes: 15 additions & 2 deletions packages/compose/src/hooks/use-media-query/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,32 @@
*/
import { useMemo, useSyncExternalStore } from '@wordpress/element';

const matchMediaCache = new Map();

/**
* A new MediaQueryList object for the media query
*
* @param {string} [query] Media Query.
* @return {MediaQueryList|null} A new object for the media query
*/
function getMediaQueryList( query ) {
if ( ! query ) {
return null;
}

let match = matchMediaCache.get( query );

if ( match ) {
return match;
}

if (
query &&
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function'
) {
return window.matchMedia( query );
match = window.matchMedia( query );
matchMediaCache.set( query, match );
return match;
}

return null;
Expand Down
9 changes: 5 additions & 4 deletions packages/compose/src/hooks/use-media-query/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* External dependencies
*/
import { act, render } from '@testing-library/react';
import { matchMedia, setMedia, cleanup } from 'mock-match-media';
import { matchMedia, setMedia } from 'mock-match-media';

/**
* Internal dependencies
Expand All @@ -26,10 +26,11 @@ describe( 'useMediaQuery', () => {
} );

afterEach( () => {
cleanup();
// Do not clean up, this will break our cache. Browsers also do not
// reset media queries.
} );

it( 'should return true when query matches', async () => {
it( 'should return true when the query matches', async () => {
const { container } = render(
<TestComponent query="(min-width: 782px)" />
);
Expand All @@ -53,7 +54,7 @@ describe( 'useMediaQuery', () => {
expect( container ).toHaveTextContent( 'useMediaQuery: false' );
} );

it( 'should return false when the query does not matches', async () => {
it( 'should return false when the query does not match', async () => {
const { container } = render(
<TestComponent query="(max-width: 782px)" />
);
Expand Down

0 comments on commit e6c62c8

Please sign in to comment.