npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-media

v1.5.0

Published

useMedia React hook

Downloads

186,138

Readme

use-media

useMedia React sensor hook that tracks state of a CSS media query.

Install

You can install use-media with npm

npm install --save use-media

or with yarn

yarn add use-media

Usage

With useEffect

import useMedia from 'use-media';
// Alternatively, you can import as:
// import {useMedia} from 'use-media';

const Demo = () => {
  // Accepts an object of features to test
  const isWide = useMedia({minWidth: '1000px'});
  // Or a regular media query string
  const reduceMotion = useMedia('(prefers-reduced-motion: reduce)');

  return (
    <div>
      Screen is wide: {isWide ? '😃' : '😢'}
    </div>
  );
};

With useLayoutEffect

import {useMediaLayout} from 'use-media';

const Demo = () => {
  // Accepts an object of features to test
  const isWide = useMediaLayout({minWidth: '1000px'});
  // Or a regular media query string
  const reduceMotion = useMediaLayout('(prefers-reduced-motion: reduce)');

  return (
    <div>
      Screen is wide: {isWide ? '😃' : '😢'}
    </div>
  );
};

Testing

Depending on your testing setup, you may need to mock window.matchMedia on components that utilize the useMedia hook. Below is an example of doing this in jest:

/test-utilities/index.ts

import {mockMediaQueryList} from 'use-media/lib/useMedia';
// Types are also exported for convienence:
// import {Effect, MediaQueryObject} from 'use-media/lib/types';

export interface MockMatchMedia {
  media: string;
  matches?: boolean;
}

function getMockImplementation({media, matches = false}: MockMatchMedia) {
  const mql: MediaQueryList = {
    ...mockMediaQueryList,
    media,
    matches,
  };

  return () => mql;
}

export function jestMockMatchMedia({media, matches = false}: MockMatchMedia) {
  const mockedImplementation = getMockImplementation({media, matches});
  window.matchMedia = jest.fn().mockImplementation(mockedImplementation);
}

/components/MyComponent/MyComponent.test.tsx

const mediaQueries = {
  mobile: '(max-width: 767px)',
  prefersReducedMotion: '(prefers-reduced-motion: reduce)',
};

describe('<MyComponent />', () => {
  const defaultProps: Props = {
    duration: 100,
  };

  afterEach(() => {
    jestMockMatchMedia({
      media: mediaQueries.prefersReducedMotion,
      matches: false,
    });
  });

  it('sets `duration` to `0` when user-agent `prefers-reduced-motion`', () => {
    jestMockMatchMedia({
      media: mediaQueries.prefersReducedMotion,
      matches: true,
    });

    const wrapper = mount(<MyComponent {...defaultProps} />);
    const child = wrapper.find(TransitionComponent);

    expect(child.prop('duration')).toBe(0);
  });
});

Storing in Context

Depending on your app, you may be using the useMedia hook to register many matchMedia listeners across multiple components. It may help to elevate these listeners to Context.

/components/MediaQueryProvider/MediaQueryProvider.tsx

import React, {createContext, useContext, useMemo} from 'react';
import useMedia from 'use-media';

interface Props {
  children: React.ReactNode;
}

export const MediaQueryContext = createContext(null);

const mediaQueries = {
  mobile: '(max-width: 767px)',
  prefersReducedMotion: '(prefers-reduced-motion: reduce)',
};

export default function MediaQueryProvider({children}: Props) {
  const mobileView = useMedia(mediaQueries.mobile);
  const prefersReducedMotion = useMedia(mediaQueries.prefersReducedMotion);
  const value = useMemo(() => ({mobileView, prefersReducedMotion}), [
    mobileView,
    prefersReducedMotion,
  ]);

  return (
    <MediaQueryContext.Provider value={value}>
      {children}
    </MediaQueryContext.Provider>
  );
}

export function useMediaQueryContext() {
  return useContext(MediaQueryContext);
}

/components/App/App.tsx

import React from 'react';
import MediaQueryProvider from '../MediaQueryProvider';
import MyComponent from '../MyComponent';

export default function App() {
  return (
    <MediaQueryProvider>
      <div id="MyApp">
        <MyComponent />
      </div>
    </MediaQueryProvider>
  );
}

/components/MyComponent/MyComponent.tsx

import React from 'react';
import {useMediaQueryContext} from '../MediaQueryProvider';

export default function MyComponent() {
  const {mobileView, prefersReducedMotion} = useMediaQueryContext();

  return (
    <div>
      <p>mobileView: {Boolean(mobileView).toString()}</p>
      <p>prefersReducedMotion: {Boolean(prefersReducedMotion).toString()}</p>
    </div>
  );
}