facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
226.72k stars 46.24k forks source link

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: #15315

Closed sethandleah closed 5 years ago

sethandleah commented 5 years ago

Hi all, I am new to react and I am trying to create a react library of components and I came across this problem because one of the components I am creating uses REACT HOOKS.

Disclaimer: this is my first time creating an issue, so please bear with me.

So I am trying to create an accordion component which toggles between these classes accordion__item--open and accordion__item to open and close.

package.json

{
  "name": "react-lib",
  "version": "0.3.0",
  "description": "A simple UI library of react components",
  "main": "dist/index.js",
  "publishConfig": {
    "registry": ""
  },
  "scripts": {
    "login": "",
    "build": "webpack --mode=production",
    "develop": "webpack --mode=development --watch"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "homepage": "",
  "dependencies": {
    "@babel/core": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.0.5",
    "eslint": "^5.15.1",
    "eslint-loader": "^2.1.2",
    "webpack": "^4.29.6",
    "webpack-cli": "^3.2.3",
    "webpack-node-externals": "^1.7.2"
  },
  "devDependencies": {
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.16.0",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.12.4",
    "eslint-plugin-react-hooks": "^1.6.0"
  }
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports =  {

  mode: 'development',
  optimization: {
    minimize: true,
  },
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'index.js',
    library: '',
    libraryTarget: 'commonjs'
  },
  target: 'node',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/react']
        }
      }
    ]
  } 
};

This is the accordion container:

import React from 'react'; 

function Accordion({ children }) {

  return (
    <div className="accordion">
      { children }
    </div>
  ); 

}

export default Accordion;

This is the accordion item that will live inside the container:

import React, { useState } from 'react'; 

function AccordionItem({header, content}) { 

const [ isActive, toggleActive ] = useState(false);

return (
    <div className={ `accordion__item ${ isActive ? 'accordion__item--open' : '' }` }>

      <button
        className="accordion__item-header"
        onClick={ () => isActive ? toggleActive(false) : toggleActive(true) }
      >
       { header }
       <svg className="icon icon--debit" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50">
         <path className="icon__path" d="M22.37,22.33V2.67a2.63,2.63,0,0,1,5.26,0V47.24a2.63,2.63,0,0,1-5.26.09V27.58H2.71a2.63,2.63,0,0,1,0-5.25Zm11.92,5.25a2.63,2.63,0,0,1,0-5.25h13a2.63,2.63,0,0,1,0,5.25Z">
         </path>
       </svg>
     </button>

     <div className="accordion__item-content">
       { children }
     </div>

   </div>
 )

};

export default AccordionItem;

Now inside of a create-react-app I import these components

My library and the create-react-app are relative to each other and I am using npm link

import React from 'react'; 

import {AccordionItem} from 'react-lib'
import {Accordion} from 'react-lib';

function App ({props}) {

  return (

      <Accordion>
        <AccordionItem header={"Hello"} content={"World"}/>
      </Accordion> 
  )

}

export default App;

I have followed all of these instructions and I still get the same error.

Current behavior?

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://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

Steps to reproduce

Expected behavior

To see the above, do the following:

import { Accordion } from 'react-lib';
import { AccordionItem } from 'react-lib';

Versions of React, Browser / OS are affected by this issue:

threepointone commented 5 years ago

I think you're facing the same issue as the folks in https://github.com/facebook/react/issues/13991 Could you have a look at some of the workarounds presented at the very bottom of the issue and see of they work for you?

revskill10 commented 5 years ago

This happens if i use hook inside a HOC.

const HOC = Component => {
  return (props) => {
    const [val] = useState();
    return <div>{val}</div>
  }
}
threepointone commented 5 years ago

@revskill10 please make a separate issue with a codesandbox repro.

iAmServerless commented 5 years ago

I will recommend you to use https://www.npmjs.com/package/webpack-bundle-analyzer.

It happens we often forgot to link react and react-dom to parent application in case of libraries which add two builds of react and leads to this issue.

If that's the case than just npm link react and react-dom to parent version of react and react-dom.

gaearon commented 5 years ago

My library and the create-react-app are relative to each other and I am using npm link

Did you read this part?

https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

It directly addresses the link workflow:

Screen Shot 2019-04-04 at 09 28 47
gaearon commented 5 years ago

(Let me know if this doesn't help and we can reopen. I appreciate the detailed writeup.)

sethandleah commented 5 years ago

Thanks, everyone for pitching in

@gaearon I had already tried and retried resolving this according to the recommendations from the React page:

I have followed all of these instructions and I still get the same error.

@threepointone funny enough so many people have found solutions to this at #13991 and I have spent the rest of yesterday implementing them with no success.

gaearon commented 5 years ago

Ok, if this didn’t help let’s leave it open so somebody can debug your issue and help you. The problem is the same (the way you link packages causes them to be duplicated in the bundle) but I’m not sure why the suggestion didn’t work for you.

sethandleah commented 5 years ago

@gaearon you can now close it, the solution above worked.

worapolburaphan commented 5 years ago

I just call hook in a very very basic way.

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

function App() {
const [number, setNumber] = useState(0);
const increase = () => {
    setNumber(number+1);
}
return <div>
<span>Counting: {number}</span>
<button onClick={increase} >Increase</button>
</div>
}

const selector = document.getElementById('app');

ReactDOM.render(<App />, selector);

I get Error Hooks can only be called inside of the body of a function component. I have create a lot of react project from sketch but I never get this error before. I understand all rules of hook. I spend a time for 12 hours to debug and solve it, But unfortunately I can't, Now I have no idea.

// Add this in node_modules/react-dom/index.js
window.React1 = require('react');

// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2); // I get true
carlosriveros commented 5 years ago

@xeastcrast were you able to solve the issue?

worapolburaphan commented 5 years ago

@carlosriveros Case 1: You might be check your index.html that only have one script tag bundle

If you get the same error after you check index.html Case 2: If you use Webpack html, In plugins property inside webpack.config file And not have {reject: true} in option of new HTMLWebpackPlugin();

You must remove script tag that src to your bundle in index.html

Because HTMLWebpackPlugin will add script tag that include your bundle file automatically.

B4BIPIN commented 5 years ago

Hi there, I am new to React Hooks. I just used Material-UI for creating Search Bar in my project. I wrote this code, but this is not working and giving the same issue. I read React Hooks docs but not got nothing regarding this. REACTJS CODE

import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import InputBase from '@material-ui/core/InputBase';
import IconButton from '@material-ui/core/IconButton';
import SearchIcon from '@material-ui/icons/Search';

const useStyles = makeStyles({
  root: {
    padding: '2px 4px',
    display: 'flex',
    alignItems: 'center',
    width: 400,
  },
  input: {
    marginLeft: 8,
    flex: 1,
  },
  iconButton: {
    padding: 10,
  },
  divider: {
    width: 1,
    height: 28,
    margin: 4,
  },
});

function Feature() {
    const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <InputBase className={classes.input} placeholder="Search Google Maps" />
      <IconButton className={classes.iconButton} aria-label="Search">
        <SearchIcon />
      </IconButton>
    </Paper>
  );
}

export default Feature;

PACKAGE.JSON

  "name": "builder-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.0.1",
    "@material-ui/docs": "^3.0.0-alpha.9",
    "@material-ui/icons": "^4.0.0",
    "@material-ui/styles": "^4.0.1",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

VERSION

EXPECTED RESULT

TRY Try to run in CODESANDBOX, everything runs fine Check it.

stupidsongshu commented 5 years ago

Hi there, I am new to React Hooks. I just used Material-UI for creating Search Bar in my project. I wrote this code, but this is not working and giving the same issue. I read React Hooks docs but not got nothing regarding this. REACTJS CODE

import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import InputBase from '@material-ui/core/InputBase';
import IconButton from '@material-ui/core/IconButton';
import SearchIcon from '@material-ui/icons/Search';

const useStyles = makeStyles({
  root: {
    padding: '2px 4px',
    display: 'flex',
    alignItems: 'center',
    width: 400,
  },
  input: {
    marginLeft: 8,
    flex: 1,
  },
  iconButton: {
    padding: 10,
  },
  divider: {
    width: 1,
    height: 28,
    margin: 4,
  },
});

function Feature() {
    const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <InputBase className={classes.input} placeholder="Search Google Maps" />
      <IconButton className={classes.iconButton} aria-label="Search">
        <SearchIcon />
      </IconButton>
    </Paper>
  );
}

export default Feature;

PACKAGE.JSON

  "name": "builder-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.0.1",
    "@material-ui/docs": "^3.0.0-alpha.9",
    "@material-ui/icons": "^4.0.0",
    "@material-ui/styles": "^4.0.1",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

VERSION

  • Node -- v10.15.3
  • React -- ^16.8.5
  • Material-UI -- ^4.0.1

EXPECTED RESULT

  • Built-in VS CODE and expected A search bar OUTPUT TypeError: Object(...) is not a function 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:

TRY Try to run in CODESANDBOX, everything runs fine Check it.

I also meet this question when using material-ui.

B4BIPIN commented 5 years ago

@stupidsongshu, so how you solved it?

vcibel commented 5 years ago

Hi there, I am new to React Hooks. I just used Material-UI for creating Search Bar in my project. I wrote this code, but this is not working and giving the same issue. I read React Hooks docs but not got nothing regarding this. REACTJS CODE

import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import InputBase from '@material-ui/core/InputBase';
import IconButton from '@material-ui/core/IconButton';
import SearchIcon from '@material-ui/icons/Search';

const useStyles = makeStyles({
  root: {
    padding: '2px 4px',
    display: 'flex',
    alignItems: 'center',
    width: 400,
  },
  input: {
    marginLeft: 8,
    flex: 1,
  },
  iconButton: {
    padding: 10,
  },
  divider: {
    width: 1,
    height: 28,
    margin: 4,
  },
});

function Feature() {
    const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <InputBase className={classes.input} placeholder="Search Google Maps" />
      <IconButton className={classes.iconButton} aria-label="Search">
        <SearchIcon />
      </IconButton>
    </Paper>
  );
}

export default Feature;

PACKAGE.JSON

  "name": "builder-frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.0.1",
    "@material-ui/docs": "^3.0.0-alpha.9",
    "@material-ui/icons": "^4.0.0",
    "@material-ui/styles": "^4.0.1",
    "react": "^16.8.5",
    "react-dom": "^16.8.5",
    "react-redux": "^6.0.1",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

VERSION

  • Node -- v10.15.3
  • React -- ^16.8.5
  • Material-UI -- ^4.0.1

EXPECTED RESULT

  • Built-in VS CODE and expected A search bar OUTPUT TypeError: Object(...) is not a function 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:

TRY Try to run in CODESANDBOX, everything runs fine Check it.

This happend to me today and I just run npm install --save react-dom@latest

https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

miguelmota commented 5 years ago

I followed the instructions provided in the help page but it still didn't resolve the problem

mikeaustin commented 5 years ago

For me, we solved it for now by simply passing React around as a prop. This is an app and separate modules that we have full control of though, so I don't know if it applies to everyone.

Barathwaja commented 5 years ago

It didn't help me out too.. Using React & React-DOM = 16.8.0 and Material-UI = 4.1.3

tquiroga commented 5 years ago

I have been testing all solutions about this hooks problem, any import of a component from an external lib using hooks will crash as there is 2 reacts instances (one from the lib, one from my app).

I've followed all suggestions, nothing has been working so far. I'm gonna make component with a state until it gets clarified further ...

devdudeio commented 5 years ago

Same Issue here. We have a Project with two react instances. One as lib and one app that is consuming the lib.

gtgalone commented 5 years ago

I solve with removing yarn.lock, package-lock.json, node_modules, dist, kind of cache and build files and then run yarn or npm install for install libraries again. Now it works!

xyj404 commented 5 years ago

I solve this by change

                <Route key={index} render={route.component} path={route.path} />

to

                <Route key={index} component={route.component} path={route.path} />

but I don't know why :(

MikeQin commented 5 years ago

Fixed by using component instead of render by mistake. The official guide didn't mention this scenario. Thanks, xyj404 <Route path="/login" exact component={LoginForm} />

raza-jamil-harvest commented 5 years ago

I had the same problem but the cause was different. For anyone using auto-import plugins or snippets make sure you import from the same case react.

If you have mix of import {useEffect} from 'react' and import {useEffect} from 'React' you will run into this issue.

AnimeManna commented 5 years ago

I also have this problem, though everything works fine for me in the storybook, but when used in the application it gives the same error

hugo-integrate commented 5 years ago

same problem too works fine in storybook , but using the app throws this error

simonepizzamiglio commented 5 years ago

Same error, I get it when I run npm test but the app works fine. Here's my package.json, any suggestions? I am really stuck and wasting time dealing with this error

{
  "name": "myproject",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@date-io/moment": "1.0.1",
    "@material-ui/core": "^3.9.3",
    "@material-ui/icons": "^3.0.1",
    "animate.css": "^3.7.0",
    "aws-amplify": "^0.4.8",
    "aws-amplify-react": "^0.1.54",
    "axios": "^0.18.0",
    "file-saver": "^2.0.0",
    "ics-js": "^0.10.2",
    "material-ui-pickers": "2.1.1",
    "moment": "^2.23.0",
    "normalize.css": "^8.0.1",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.0",
    "react-date-range": "^1.0.0-beta",
    "react-dom": "^16.8.6",
    "react-google-maps": "^9.4.5",
    "react-jss": "^8.6.1",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "3.0.1",
    "recharts": "^1.3.5",
    "redux": "^4.0.1",
    "styled-components": "^4.2.0",
    "sweetalert2": "^7.33.1",
    "sweetalert2-react-content": "^1.0.1"
  },
  "scripts": {
    "start:dev": "node  -r dotenv/config ./node_modules/react-scripts/bin/react-scripts start dotenv_config_path=./env/development.env",
    "start:stage": "node -r dotenv/config ./node_modules/react-scripts/bin/react-scripts start dotenv_config_path=./env/stage.env",
    "start:prod": "node -r dotenv/config ./node_modules/react-scripts/bin/react-scripts start dotenv_config_path=./env/production.env",
    "build:stage": "node --max_old_space_size=2048 --max_old_space_size=1024 -r dotenv/config ./node_modules/.bin/react-scripts build dotenv_config_path=./env/stage.env",
    "build:dev": "node --max_old_space_size=2048 -r dotenv/config ./node_modules/react-scripts/bin/react-scripts build dotenv_config_path=./env/development.env",
    "build:prod": "node --max_old_space_size=2048 -r dotenv/config ./node_modules/react-scripts/bin/react-scripts build dotenv_config_path=./env/production.env",
    "test": "node -r dotenv/config ./node_modules/.bin/react-scripts test dotenv_config_path=./env/development.env --runInBand",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^4.0.0",
    "@testing-library/react": "^8.0.5",
    "@testing-library/react-hooks": "^1.1.0",
    "dotenv": "^6.0.0",
    "prettier": "^1.15.3",
    "react-test-renderer": "^16.8.6"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}
pmjonesg commented 5 years ago

Ran into this situation as well using react and react-dom both v16.8.6, using the makeStyles hook from @material-ui/core in a separate app linked using npm link.

After upgrading the main app to react and react-dom v16.9.0, and relinking the app that was using the hooks causing the issue, everything started working again.

bachphuc commented 5 years ago

Yeah, I had same issue when I use @material-ui. It takes more time to figure out this issue. Then I searched google and found a solution for this. It's here http://putridparrot.com/blog/react-material-ui-invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-component/

Original post:

When looking through some examples of writing Material UI code within React and using TypeScript (within a .tsx file to be precise) you might come across an error at runtime such as “Invalid hook call. Hooks can only be called inside of the body of a function component”.

Here’s an example of the code which causes this error

import React, { Component }  from "react";
import AddIcon from "@material-ui/icons/Add";
import { Fab } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles(theme => ({
   fab: {
      margin: theme.spacing(1),
   },
}));

const classes = useStyles();

export default class SampleComponent extends Component<{}, {}> {
   public render() {
      return (
         <div>
            <Fab color="primary" aria-label="Add" className={classes.fab}><AddIcon /></Fab>
         </div>
       );
   }
}

What we need to do is wrap the useStyles code in a function and replace the code which uses it, so for example

const SampleFab = () => {
   const classes = useStyles();
   return <Fab color="primary" aria-label="Add" className={classes.fab}><AddIcon /></Fab>;
}

export default class SampleComponent extends Component<{}, {}> {
   public render() {
      return (
         <div>
            <SampleFab />
         </div>
      );
   }
}

This also shows how we can create reusable components from just a simple function.

=> It's crazy but It's working well. Hope this can help.

sourcesoft commented 5 years ago

If you're using lerna or a monorepo like me, add sth like this to your Webpack resolve config

...
    alias: {
      'react-dom': 'path/to/main-package/node_modules/react-dom',
      react: 'path/to/main-package/form/node_modules/react',
    }
...

If you're getting it in Storybook, add it to custom Webpack config there too.

A side note, if this fixes the issue for you, your webpack built bundle also had 2 versions of react in it (use sth like webpack bundle analyzer to inspect it). In my case, I had a separate package in my monorepo that took care of bundling and all the tooling so I had to add an alias.

mysteryven commented 4 years ago

If you're using lerna or a monorepo like me, add sth like this to your Webpack resolve config

...
    alias: {
      'react-dom': 'path/to/main-package/node_modules/react-dom',
      react: 'path/to/main-package/form/node_modules/react',
  }
...

If you're getting it in Storybook, add it to custom Webpack config there too.

A side note, if this fixes the issue for you, your webpack built bundle also had 2 versions of react in it (use sth like webpack bundle analyzer to inspect it). In my case, I had a separate package in my monorepo that took care of bundling and all the tooling so I had to add an alias.

Thank you, that's solved my problem, I installed another React in my docs dictory, which caused this problem.

jafartke commented 4 years ago

I just call hook in a very very basic way.

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

function App() {
const [number, setNumber] = useState(0);
const increase = () => {
    setNumber(number+1);
}
return <div>
<span>Counting: {number}</span>
<button onClick={increase} >Increase</button>
</div>
}

const selector = document.getElementById('app');

ReactDOM.render(<App />, selector);

I get Error Hooks can only be called inside of the body of a function component. I have create a lot of react project from sketch but I never get this error before. I understand all rules of hook. I spend a time for 12 hours to debug and solve it, But unfortunately I can't, Now I have no idea.

// Add this in node_modules/react-dom/index.js
window.React1 = require('react');

// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2); // I get true

You might have mismatching versions of React and React DOM. I had same issue solved by making change in React version

abdulmoizshaikh commented 4 years ago

I have face this issue when I try to change my component from functional to classfull component and I also get this error so here is my solution regarding this error hope it helps in your case also.

try use higher order component in this case

import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/styles'; import Button from '@material-ui/core/Button';

const styles = theme => ({ root: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, padding: '0 30px', }, });

class HigherOrderComponent extends React.Component {

render(){ const { classes } = this.props; return (

  );

} }

HigherOrderComponent.propTypes = { classes: PropTypes.object.isRequired, };

export default withStyles(styles)(HigherOrderComponent);

fabd commented 4 years ago

I am learning React and FWIW, I also saw the issue when trying to render App() like this:

ReactDOM.render(App(), $("#root"));

My reasoning was that <App />would implicitly create a mini template just to insert the App component, so instead I just called App directly, which returns the JSX template.

However, once I started using setState(), it caused the aforementioned issue. Changing to <App /> solved this.

ReactDOM.render(<App />, $("#root"));

note: $ is just a helper const $ = sel => document.querySelector(sel);

dbeaudway commented 4 years ago

For those who are still encountering this error after troubleshooting all the proposed fixes, double-check that you are using the correct directory casing when running your project. I continued to have problems on my PC and discovered this was the reason why.

https://stackoverflow.com/questions/58365151/hooks-error-invalid-hook-call-using-nextjs-or-reactjs-on-windows

joselcc commented 4 years ago

I was getting that error when running test after updating react-dom to version 16.10.2. Upgrading enzyme-adapter-react-16 to version 1.15.1 fixed it

rockneverdies55 commented 4 years ago

Oh man I'm on react v16.10.2. I already spent couple of hours trying fighting this but I won't continue this battle anymore since I have more important things to do. I'm ok with staying on react-final-form 4.1.0 for now. What a frustration.

DanielAllt commented 4 years ago

This solved my problem:

https://github.com/facebook/create-react-app/issues/7676#issuecomment-531543375

pluma commented 4 years ago

I've had the same problem just now after upgrading dependencies and spent hours trying to nail this down.

npm ls react showed the following:

├─┬ @storybook/addon-info@5.2.6
│ └── react@16.9.0
└── react@16.12.0

Pinning react and react-dom to 16.9.0 made the error go away because it made the transient dependency go away. I first thought this meant there was a regression in 16.10.0 until I noticed the problem also occurred in 16.8.6 (because the transient dependency was apparently pinned).

Turns out yarn's resolutions field is a bit finicky to get to work right, especially in lerna monorepos, but eliminating the second copy of React did the trick. I still have no idea how it even ended up in the bundle but that's what caused the problem.

I'm now considering dropping @storybook/addon-info completely as it also relies on another dependency that has a dependency on React 0.14 (yes), although that one somehow hasn't caused problems yet.

EDIT: For the record, I spent about four hours on this as I couldn't get resolutions to eliminate the duplicate and refused to believe that copy of React even got into the bundle. Don't be like me. Deduplicate your transient Reacts.

Neeraj-swarnkar commented 4 years ago

This happens if i use hook inside a HOC.

const HOC = Component => {
  return (props) => {
    const [val] = useState();
    return <div>{val}</div>
  }
}

I am also facing the same issue.

https://stackoverflow.com/questions/59173968/react-error-hooks-can-only-be-called-inside-the-body-of-a-function-component?noredirect=1#comment104570333_59173968

can you please guide me ?

pluma commented 4 years ago

@Neeraj-swarnkar Try reducing your problem to a minimal example that still results in the error.

It almost always boils down to one of two problems:

Sadly the stack traces tend to be misleading in this case but the error messages generally give you the right idea.

Neeraj-swarnkar commented 4 years ago

@Neeraj-swarnkar Try reducing your problem to a minimal example that still results in the error.

It almost always boils down to one of two problems:

  • you think you're passing a component but it's actually a render prop (i.e. a the "component" is being called as a function, not a component)
  • you've somehow bundled more than one version of React via your transient dependencies and they step on each others' toes

Sadly the stack traces tend to be misleading in this case but the error messages generally give you the right idea.

Thanks for the pointer, can you guide me what could be done better or what should i do to fix this ?

pluma commented 4 years ago

@Neeraj-swarnkar try commenting out code and replacing it with placeholders until you have a minimal example that still results in the same error.

If you don't have a colleague or peer you can ask to assist you in debugging this further, see if you can find a local meetup, study group or a company that does open office hours and ask them for help. If all else fails, hire someone to look into it for you.

ladifire commented 4 years ago

My library and the create-react-app are relative to each other and I am using npm link

Did you read this part?

https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

It directly addresses the link workflow:

Screen Shot 2019-04-04 at 09 28 47

This work like a charm!

ladifire commented 4 years ago

My library and the create-react-app are relative to each other and I am using npm link

Did you read this part?

https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

It directly addresses the link workflow:

Screen Shot 2019-04-04 at 09 28 47

This work like a charm!

ZeldaYuan commented 4 years ago

I solved this problem yesterday, it bothered me for half month.Yesterday I short the code to very little (just add )and still got this invalid hook call problem.And it made me suddenly realized what mistake I did here, I didn't install the react-redux software in that folder. I have installed this software in the other project folder,so I didn't realized this one also need it.After I install it, it PASS this ERROR. Hope this advice may help someone who has the same mistake as I did before.

qtwwyl commented 4 years ago

I solve this by change

                <Route key={index} render={route.component} path={route.path} />

to

                <Route key={index} component={route.component} path={route.path} />

but I don't know why :(

It does work for me, but I dont know why either.

benlinton commented 4 years ago

If you're coming here because you're using a HOC + makeStyles from Material UI, here is your answer: https://stackoverflow.com/questions/56329992/invalid-hook-call-hooks-can-only-be-called-inside-of-the-body-of-a-function-com

pluma commented 4 years ago

I solve this by change

                <Route key={index} render={route.component} path={route.path} />

to

                <Route key={index} component={route.component} path={route.path} />

but I don't know why :(

It does work for me, but I dont know why either.

The "component" prop expects a React component, the "render" prop expects a function that will be invoked as a function. Function components are components, invoking them as normal functions doesn't work if they use hooks and generally isn't a good idea.