[reactjs] Invalid hook call. Hooks can only be called inside of the body of a function component

I am new to React and Now I would like to show some record in the table and now I got this error. Help me, please.

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 for tips about how to debug and fix this problem.

import React,{Component} from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles(theme => ({
    root: {
      width: '100%',
      marginTop: theme.spacing(3),
      overflowX: 'auto',
    },
    table: {
      minWidth: 650,
    },
  }));

class allowance extends Component{
    constructor(){
        super();
        this.state={
            allowances:[],
        };

    }

    componentWillMount() {
        fetch('http://127.0.0.1:8000/allowances')
        .then(data=>{  

            return data.json();      

        }).then(data=> {          

            this.setState({allowances : data});

            console.log("allowance state",this.state.allowances);
        })

    }



    render() {
        const classes = useStyles();
        return (
            <Paper className={classes.root}>
              <Table className={classes.table}>
                <TableHead>
                  <TableRow>
                    <TableCell>Allow ID</TableCell>
                    <TableCell align="right">Description</TableCell>
                    <TableCell align="right">Allow Amount</TableCell>
                    <TableCell align="right">AllowType</TableCell>

                  </TableRow>
                </TableHead>
                <TableBody>
                  {this.state.allowances.map(row => (
                    <TableRow key={row.id}>
                      <TableCell component="th" scope="row">
                        {row.AllowID}
                      </TableCell>
                      <TableCell align="right">{row.AllowDesc}</TableCell>
                      <TableCell align="right">{row.AllowAmt}</TableCell>
                      <TableCell align="right">{row.AllowType}</TableCell>                    
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Paper>
          );}

}

export default allowance;

This question is related to reactjs material-ui react-hooks

The answer is


Yesterday, I shortened the code (just added <Provider store={store}>) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.

I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.


I have just started using hooks and I got the above warning when i was calling useEffect inside a function:

Then I have to move the useEffect outside of the function as belows:

 const onChangeRetypePassword = async value => {
  await setRePassword(value);
//previously useEffect was here

  };
//useEffect outside of func 

 useEffect(() => {
  if (password !== rePassword) {
  setPasswdMismatch(true);

     } 
  else{
    setPasswdMismatch(false);
 }
}, [rePassword]);

Hope it will be helpful to someone !


Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.


If all the above doesn't work, especially if having big size dependency (like my case), both building and loading were taking a minimum of 15 seconds, so it seems the delay gave a false message "Invalid hook call." So what you can do is give some time to ensure the build is completed before testing.


You can convert class component to hooks,but Material v4 has a withStyles HOC. https://material-ui.com/styles/basics/#higher-order-component-api Using this HOC you can keep your code unchanged.


React linter assumes every method starting with use as hooks and hooks doesn't work inside classes. by renaming const useStyles into anything else that doesn't starts with use like const myStyles you are good to go.

Update:

makeStyles is hook api and you can't use that inside classes. you can use styled components API. see here


happens also when you use a dependency without installing it. happen to me when i called MenuIcon from '@material-ui/icons/' when was missing in the project.


Caught this error: found solution.

For some reason, there were 2 onClick attributes on my tag. Be careful with using your or somebodies' custom components, maybe some of them already have onClick attribute.


complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

I had this issue when I used npm link to install my local library, which I've built using cra. I found the answer here. Which literally says:

This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming 'myapp' and 'mylib' are sibling folders, one possible fix is to run 'npm link ../myapp/node_modules/react' from 'mylib'. This should make the library use the application’s React copy.

Thus, running the command: npm link ../../libraries/core/decipher/node_modules/react from my project folder has fixed the issue.


In my case, I was trying to use mdbreact on windows. Though it installed, But i was getting the above error. I had to reinstall it and everything was ok. It happened to me once two with antd Library


For me , the error was calling the function useState outside the function default exported


You can use "export default" by calling an Arrow Function that returns its React.Component by passing it through the MaterialUI class object props, which in turn will be used within the Component render ().

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}

export default () => {
    const classes = useStyles();
    return (
        <AllowanceClass classes={classes} />
    )
}

This error can also occur when you make the mistake of declaring useDispatch from react-redux the wrong way: when you go:
const dispatch = useDispatch instead of:
const dispatch = useDispatch(); (i.e remember to add the parenthesis)


My case.... SOLUTION in HOOKS

const [cep, setCep] = useState('');
const mounted = useRef(false);

useEffect(() => {
    if (mounted.current) {
        fetchAPI();
      } else {
        mounted.current = true;
      }
}, [cep]);

const setParams = (_cep) => {
    if (cep !== _cep || cep === '') {
        setCep(_cep);
    }
};

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to material-ui

Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop How to center a component in Material-UI and make it responsive? How to get input textfield values when enter key is pressed in react js? Changing the URL in react-router v4 without using Redirect or Link Material UI and Grid system What does the error "JSX element type '...' does not have any construct or call signatures" mean? How get data from material-ui TextField, DropDownMenu components?

Examples related to react-hooks

Invalid hook call. Hooks can only be called inside of the body of a function component React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? react hooks useEffect() cleanup for only componentWillUnmount? How to use callback with useState hook in react Push method in React Hooks (useState)? React Hooks useState() with Object useState set method not reflecting change immediately React hooks useState Array Can I set state inside a useEffect hook