Skip to content

useMediaQuery

This example shows how to create a custom hook to use media queries.

Edit use-mutable-source-gsap

tsx
import { usePureSource } from 'use-mutable-source';

function useMediaQuery(mediaQuery: string) {
  const [useSnapshot] = usePureSource(
    // Generates the mediaQueryList.
    () => window.matchMedia(mediaQuery),
    // Generates a new mediaQueryList when the query changes.
    [mediaQuery]
  );

  return useSnapshot(
    // Derives the snapshot.
    (mediaQueryList) => mediaQueryList.matches,
    // Handles the subscription.
    (mediaQueryList, onChange) => {
      // Subscribe to changes.
      mediaQueryList.addEventListener('change', onChange);
      // Returns a callback to unsubscribe.
      return () => mediaQueryList.removeEventListener('change', onChange);
    }
  );
}

Released under the MIT License.