0

I need to show a dialog only on small screens. After researching I found out that there is a hook called useMediaQuery() which returns a boolean if the browser meets a specific resolution.

I'm using "@mui/material": "^5.1.1"

This is my implementation:

import { useTheme, useMediaQuery, Dialog, DialogTitle } from '@mui/material';
import { useEffect, useState } from 'react';

const MyDialog = () => {
    const theme = useTheme();
    const [dialogOpen, setDialogOpen] = useState(false);

    useEffect(() => {
        setDialogOpen(useMediaQuery(theme.breakpoints.down('lg')));
    });


    return (
        <Dialog open={dialogOpen}>
            <DialogTitle>This is a test Dialog Title</DialogTitle>
        </Dialog>
    );
};

However this is giving me the error:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

It seems it doesn't allow me to use hooks instide the useEffect hook. How can I fix it otherwise, in order to achieve the same result, which is to update the useState state true or false according to the resolution of the browser?

Pikk
  • 2,343
  • 6
  • 25
  • 41

2 Answers2

1

You cannot use hooks inside a hook call (useMediaQuery in the callback of useEffect) even though you can use hooks inside another hook definition.

Fix it by moving useMediaQuery to the top level of MyDialog component. Then use the output value in useEffect.

import { useTheme, useMediaQuery, Dialog, DialogTitle } from "@mui/material";
import { useEffect, useState } from "react";

const MyDialog = () => {
  const theme = useTheme();
  const [dialogOpen, setDialogOpen] = useState(false);

  const matches = useMediaQuery(theme.breakpoints.down("lg"));
  
  useEffect(() => {
    setDialogOpen(matches);
  });

  return (
    <Dialog open={dialogOpen}>
      <DialogTitle>This is a test Dialog Title</DialogTitle>
    </Dialog>
  );
};
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
1

Hook should be called only on top level

You can only call Hooks while React is rendering a function component:

✅ Call them at the top level in the body of a function component. ✅ Call them at the top level in the body of a custom Hook.

const theme = useTheme();    
const mediaQuery = useMediaQuery(theme.breakpoints.down('lg'))

Try to do setState only on mount to avoid infinite re-renders, Since you're computing browser specification setDialogOpen can be set once.

useEffect(() => {
  setDialogOpen(mediaQuery);
},[]);

Read more about your error here

Shan
  • 1,468
  • 2
  • 12