'React - Invalid hook call. Hooks can only be called inside of the body of a function component

I created a react module and then a react app using create-react-app When I run the App I get the following error in the browser:

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

Inspecting my app with chrome dev tools I noticed the evidence of the problem: webpack/babel loads my module's node_modules in the browser and so 2 version of react (and any peerDependencies) are there:

enter image description here

Is there a way to tell to my app to exclude any module's node_modules folder?

Thanks for your help.



Solution 1:[1]

I fixed this issue following the approach mentioned here using react-app-rewired and customize-cra.

You can find an example project here: https://github.com/dwjohnston/material-ui-hooks-issue/tree/master

I think this can be useful for others with the same issue.

Ciao

Solution 2:[2]

If anyone stumbles upon this error and none of the standard solutions are helping, you may have the same situation as I just had.

My code tried to import a hook from a package that wasn't installed (@material-ui in my case). Instead of warning me that the package wasn't installed, I received the above error.

Code sample:

import { makeStyles } from "@material-ui/core/styles"
const useStyles = makeStyles({
   ...
});
function MyComponent() {
   const classes = useStyles();
}

Solution 3:[3]

Fixed it by editing index.html. Just moved tag with bundle in the head of the page. I don't know if it's a good solution, but still works

like this

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8"/>
            <title>Test</title>
            <script src="bundle.js"></script>
        </head>
        <body>
            <div id="root"></div>
        </body>
    </html>

The script tag was in the body (moveed it to the head), cause when I started to create the project I just copied it from example.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emilio Petrangeli
Solution 2 Hacktisch
Solution 3