skip to Main Content

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


  1. I would probably create useIsMobile hook and use it everywhere:

    import { useMediaQuery, useTheme } from "@mui/material";
    
    const useIsMobile = () => useMediaQuery(useTheme().breakpoints.down("sm"));
    

    Usage:

    function Component1 () {
      const isMobile = useIsMobile();
    }
    
    Login or Signup to reply.
  2. 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.

    <Box
      sx={{
        width: {
          xs: 100, // theme.breakpoints.up('xs')
          sm: 200, // theme.breakpoints.up('sm')
          md: 300, // theme.breakpoints.up('md')
          lg: 400, // theme.breakpoints.up('lg')
          xl: 500, // theme.breakpoints.up('xl')
        },
      }}
    >
      This box has a responsive width.
    </Box>
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search