How the useMediaQuery hook works?

Martha Rodríguez
1 min readDec 1, 2020

--

The useMediaQuery is a hook that material UI uses to match a CSS media query, it helps when you want to render o not a component depending on the screen size.

What is a media query?

A media query lets you add some conditional styles, with the @media or @import rules.

In this case, the element with the facet_sidebar class will be hidden when the screen is smaller than 600px.

Also, you can test and monitor the media state using the methods Window.matchMedia() andMediaQueryList.addListener().

Basically, you pass a parameter to the media query indicating the maximum or minimum size of the screen you need. It works as a condition, so if you passed a max-width: 700px as the parameter, it will check if the screen size is smaller than 700px, so all the styles inside the rule will be applied when this condition is true.

What does useMediaQuery do?

The useMediaQuery hook receives a media rule as a parameter and it returns true if it matches with the screen size, and false if it doesn’t.

In this case, we will see in the screen “(min-width:600px) matches: true” until the screen size is smaller than 600px.

You can add conditions to do any action you need depending on if it matches or not.

How is it built?

You can see the useMediaQuery file here. In the next block of code, we can see how a match is updated using the React state, and basically uses the matchMedia function to match the media query that was sent as a parameter.

After assigning a value to the match constant, it is returned at the end of the file.

Media queries are so useful for build responsive projects, and this hook helps to make it easier for Material UI implementation.

--

--

Martha Rodríguez

Hello World!👋🏽 I’m a programmer in development. I’ll share with you my sketch notes about everything I learn during my journey as an Encora Intern…and more 😉