Skip to content

Instantly share code, notes, and snippets.

@tbremer
Last active October 15, 2019 21:17
Show Gist options
  • Save tbremer/1cec5558d1acb686c761838600606c6b to your computer and use it in GitHub Desktop.
Save tbremer/1cec5558d1acb686c761838600606c6b to your computer and use it in GitHub Desktop.
React `useMatchMedia` hook

useMatchMedia Hook

This hook takes a media query string and returns an array with a boolean (matches) and a way to set the media query (setMediaQuery)

Example: https://codepen.io/tbremer/pen/QWWEwXr?editors=1010

To use:

function Application() {
  const [matches] = useMatchMedia('(max-width: 600px)');

  return (
    <div style={{ color: matches ? 'blue' : 'red' }}>
      <h1>Welcome to React v{React.version}!</h1>
    </div>
  );
}

ReactDOM.render(
  <Application />,
  document.getElementById('app')
);

API

useMatchMedia(query: string): returns an array with two items

[
  matches: boolean,
  setMediaQuery: (string) => void // function that takes a query (string) as it's argument.
]
import React from 'react';
export default function useMatchMedia(query) {
const [mediaQueryList, setMediaQuery] = React.useState(window.matchMedia(query));
const [matches, setMatch] = React.useState(mediaQueryList.matches);
React.useEffect(() => {
mediaQueryList.addListener(evt => setMatch(evt.matches))
}, []);
return [matches, setMediaQuery];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment