How the useMediaQuery hook works?
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.
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.
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.