score:82

Accepted answer

you can only call hooks from react functions. read more here.

just convert the allowance class component to a functional component.

working codesandbox demo.

const allowance = () => {
  const [allowances, setallowances] = usestate([]);

  useeffect(() => {
    fetch("http://127.0.0.1:8000/allowances")
      .then(data => {
        return data.json();
      })
      .then(data => {
        setallowances(data);
      })
      .catch(err => {
        console.log(123123);
      });
  }, []);

  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 > {
      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;

score:-4

when you face this issue you just need to reinstall this "npm install react-bootstrap@next bootstrap@5.1.0" then your error will be resolve.

score:-2

to anybody who might looking for a fast solution to this issue :

you might be breaking the rules of hooks. to solve this problem move the :

👉const [x, setx] = usestate(0);

to the top-level of the function that calling it and not outside of the function.

function app() {
   👉const [t, settime] = usestate("");

   return (
      <div>
         <h1>{t}</h1>
         <button onclick={() => settime(t+1)}>get time</button>
      </div>
 );
}

👍 https://reactjs.org/warnings/invalid-hook-call-warning.html

score:-2

i meet this question, my error reason is that i development project a and i link a other project b to a, but a has react package and b also has react package, they are the same version(16.13). but this cause the question, i set file means webpack.config.js, like this:

alias: {
  'react': path.join(path.resolve(__dirname), '../node_modules/react'),
},

set b react package resolve to a react package,i guess reason is that a project can not has two or more react package, even if they are the same versions. but i can not verify my guess.

score:-1

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);
    }
};

score:0

my error was with the export at the end, i had the following:

enter image description here

i should have removed the brackets:

enter image description here

score:0

i got this error when i linked a local library. the following solved my problem.

  1. in the library:
  • remove "react" and "react-dom" from dependancies and added them to peerdependencies.
  • install dependencies, build
  1. restart the main project.

score:0

another reason this error could happen is if you have declared your functional components with an arrow function signature instead of a function signature.

ex: change your functional component declaration from an arrow function

export const counter = (props) => {}

to function declaration

export function counter (props) {}

and that will help resolve the issue. at least in my case, it did.

score:1

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.

score:1

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.

score:1

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.

score:1

here's what fixed it for me. i had the folder node_modules and the files package.json and package-lock.json in my components folder as well as on the root of my project where it belongs. i deleted them from where they don't belong. don't ask me what i did to put them there, i must have done an npm something from the wrong location.

score:1

in my case, changes i've done in package-json cause to problem.

npm install react-redux

fix that

score:1

if you're using react-router-dom, make sure to call usehistory() inside the hook.

score:1

you may check your routes. if you are using render instead of component in route(<route path="/testpath" render = {(props)=><test {...props} />} />) so you properly called your component in an arrow function passing proper props to that.

score:1

be avare of import issues- for me the error was about failing imports / auto imports on components and child components. had nothing to do with functional classes vs class components.

  • this is prone to happen as vs code auto importing can specify paths that are not working.
  • if import { mycomponent } is used and export default used in the component the import should say import mycomponent
  • if some components use index.js inside their folder, as a shotcut for the path, and others not the imports might break. here again the auto import can cause problems as it merges all components form same folder as this {textcomponent, buttoncomponent, listcomponent} from '../../common'

try to comment out some components in the file that gives the error and you can test if this is the problem.

score:1

in my case, the issues was i had cd'd into the wrong directory to do my npm installs. i just re-installed the libraries in the correct directory and it worked fine!

score:1

i ran into this same issue while working on a custom node_module and using npm link for testing within a cra (create react app).

i discovered that in my custom node package, i had to add a peerdependencies

"peerdependencies": {
    "@types/react": "^16.8.6 || ^17.0.0",
    "react": "^17.0.0",
    "react-dom": "^17.0.0"
  },

after added that into my package.json, i then re-built my custom package. then in the cra, i blew away node_modules, re npm install, re-do the npm link <package>, and then start the project.

fixed everything!

score:1

if your front-end work is in its own folder you might need to install @material-ui/core @material-ui/icons inside that folder, not in the backend folder.

npm i @material-ui/core @material-ui/icons

score:2

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

score:2

this error can also occur if you're using mobx, and your functional component is wrapped in the mobx observer function. if this is the case, make sure you are using mobx-react version 6.0.0 or higher. older versions will convert your functional component to a class under the covers and all hooks will fail with this error.

see answer here: react hooks mobx: invalid hook call. hooks can only be called inside of the body of a function component

score:2

in my case i removed package-lock.json and node_modules from both projects and re-install again, and now works just fine.


// project structure


root project
- package-lock.json
- package.json // all dependencies are installed here
- node_modules

-- second project
-- package-lock.json
-- package.json 
  "dependencies": {
    "react": "file:../node_modules/react",
    "react-dom": "file:../node_modules/react-dom",
    "react-scripts": "file:../node_modules/react-scripts"
  },
-- node_modules


not sure what caused the issue in the first place, as this happened to me before and did same steps as above, and issue was resolved.

score:2

i ran into a similar issue, however my situation was a bit of an edge case.

the accepted answer should work for most people, but for anyone else using react hooks in existing react code that uses radium, note that hooks won't work without workarounds if you use radium.

in my case, i was exporting my component like so:

// this is pseudocode

const mycomponent = props => {
  const [hookvalue, sethookvalue] = usestate(0);
  return (
    // use the hook here somehow
  )
}

export default radium(mycomponent)

removing that radium wrapper from the export fixed my issue. if you need to use radium, resorting to class components and their lifecycle functions may be an easier solution.

hopefully this helps out at least just one other person.

score:3

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.

score:3

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 !

score:3

in my case, i was passing component name in flatlist's renderitem prop instead of function. it was working earlier as my component was a functional component but when i added hooks in it, it failed.

before:

    <flatlist
        data={memberlist}
        renderitem={<memberitem/>}
        keyextractor={member => member.name.split(' ').join('')}
        listemptycomponent={
          <text style={{textalign: 'center', padding: 30}}>
            no data: click above button to fetch data
          </text>
        }
      />

after:

    <flatlist
        data={memberlist}
        renderitem={({item, index}) => <memberitem item={item} key={index} />}
        keyextractor={member => member.name.split(' ').join('')}
        listemptycomponent={
          <text style={{textalign: 'center', padding: 30}}>
            no data: click above button to fetch data
          </text>
        }
      />

score:3

in my case, it was just this single line of code here which was on my app.js that caused this and made me lose 10 hours in debugging. the react native and expo could not point me to this. i did everything that was on stackoverflow and github and even the react page that was supposed to solve this and the issue persisted. i had o start taking my code apart bit by bit to get to the culprit

 **const window = usewindowdimensions();**

it was placed like this:

import * as react from 'react';
import { text, view, stylesheet, imagebackground, statusbar, image, alert, safeareaview, button, touchableopacity, usewindowdimensions } from 'react-native';
import constants from 'expo-constants';

import whooksplashscreen11 from './page1';
import screen1 from './loginpage';
import loginscreen from './login';
import registerscreen1 from './register1';
import registerscreen2 from './register2-verifnum';
import registerscreen3 from './register3';
import registerscreen4 from './register4';
import registerscreen5 from './register5';
import registerscreen6 from './register6';
import bouncycheckbox from "react-native-bouncy-checkbox";
import locationpermission from './locationpermission.js'
import selfieverif1 from './selfieverif1'
import selfieverif2 from './selfieverif2'
import addphotos from './addphotos'


// you can import from local files
import { usefonts } from 'expo-font';

// or any pure javascript modules available in npm

import { navigationcontainer } from '@react-navigation/native';
import { createnativestacknavigator } from '@react-navigation/native-stack';


//fontawesome
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab, } from '@fortawesome/free-brands-svg-icons'
import { fachecksquare, facoffee, fafilter, fasearch,  } from '@fortawesome/free-solid-svg-icons'
import { fontawesomeicon } from '@fortawesome/react-native-fontawesome'
import icon  from "react-native-vector-icons/fontawesome5";

import mytabs from './swipepage'

library.add(fab, fachecksquare, facoffee, fafilter, fasearch,);


const window = usewindowdimensions();
const stack = createnativestacknavigator();

function app() {
  return ( ....
)}

score:4

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

score:4

add this to your package.json

"peerdependencies": {
   "react": ">=16.8.0",
   "react-dom": ">=16.8.0"
}

source:https://robkendal.co.uk/blog/2019-12-22-solving-react-hooks-invalid-hook-call-warning

score:5

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);

score:6

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)

score:7

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.

score:9

for me , the error was calling the function usestate outside the function default exported

score:10

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

score:25

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} />
    )
}

score:100

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 <path_to_local_library>/node_modules/react, eg. in my case npm link ../../libraries/core/decipher/node_modules/react from the project directory has fixed the issue.


Related Query

More Query from same tag