I have this pattern of importing the useMediaQuery
and useTheme
hook from MUI and then storing them in variables in each component that needs it. I would like to store the logic somewhere else and just import isMobile
to the components that need it, should I create a custom hook or pass isMobile
around using context or something?
import { useMediaQuery, useTheme } from "@mui/material";
function Component1 () {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
...
}
import { useMediaQuery, useTheme } from "@mui/material";
function Component2 () {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
...
}
2
Answers
I would probably create
useIsMobile
hook and use it everywhere:Usage:
The straightforward answer is to extract the reusable code to a hook, as suggested in the answer from Ori Drori, but consider as well whether you really NEED an
isMobile
check in your components. If you’re only applying style or size changes based on viewport size, MUI has intelligent style attributes that understand your breakpoints, e.g.— Responsive Values in the MUI System Documentation
Note that you need to use the MUI System components instead of the Base components. If you’re already using the Core components, you’re actually using the MUI System components and no adjustment necessary.