Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the best way to clean up this logic so that I don't have to keep redeclaring a variable?

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"));
...

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading