Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React with MUI's useStyles() giving me a hooks rules violation

I'm getting the dreaded React "Invalid Hook Call" error and I'm not running any hooks.

  1. Installed React using CRA
  2. Installed MUI
  3. Built simple styles page:
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
    justifyContent: 'center',
  },
  layout: {
    minHeight: '230px',
  },
}));

export default useStyles;
  1. Added styles to component:
import React from 'react';
import useStyles from './styles';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';

const SimpleComponent = (props) => {
  const classes = useStyles();
  return (
    <React.Fragment>
      <Container className={classes.root}>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <div>Page Content</div>;
          </Grid>
        </Grid>
      </Container>
    </React.Fragment>
  );
};

export default SimpleComponent;

The app returns no errors on npm start, but the page itself gives me the invalid hook call pointing to the line const classes = useStyles();. That's not a hook.

I've tried re npm installing the app, I've tried moving the call all around, no matter what I do I get that same page. Looks like a lot of people have had similar problems with this configuration but no other solutions have addressed my problem.

Hooks Error Page:

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:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See[https://reactjs.org/warnings/invalid-hook-call-warning.html][1] for tips about how to debug and fix this problem.

SimpleComponent
src/Components/PaymentHistory/PaymentHistory.js:7
   4 | import Container from '@material-ui/core/Container';
   5 | 
   6 | const SimpleComponent = (props) => {
>  7 |   const classes = useStyles();
   8 |   return (
   9 |     <React.Fragment>
  10 |       <Container className={classes.root}>
View compiled  
like image 591
Dave Kanter Avatar asked Jan 18 '26 06:01

Dave Kanter


1 Answers

Please make sure all the dependencies(including @material-ui/core) are correctly installed.

Here is a working demo.

like image 70
hangindev.com Avatar answered Jan 19 '26 20:01

hangindev.com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!