ChatGPT解决这个技术问题 Extra ChatGPT

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

I want to show some records in a table using React but I got this error:

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: You might have mismatching versions of React and the renderer (such as React DOM) You might be breaking the Rules of Hooks 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;

t
theVoogie

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.


Thanks Mate! you saved my day! All those using locally packages via npm/yarn link, follow this!
This worked for me. This was my exact issue.
then it will cause an error when publishing on npm, right? or maybe no, since it's linked, on my machine it will use react from the link and after publishing, it will use its own. 🤔
Working on app buit with cra linked to a local library since long time, I'd never see this error message. Just run npm i on both project then npm link again and it's fine.
It took me 8 hours with this issue and trying to finish the feature in a different way. Thank you so much
A
Aryan Beezadhur

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;

One thing want to ask you, after calling setAllowances(data), allowances should have data right? otherwise, when allowances have data?
Yes. After calling setAllowances(data). setAllowances working like this.setState({allowances: data})
I was a bit confused, after calling setAllowances(data), I try like console.log("data",data); and this has 3 records but if I try like console.log("allowance",allowances); this is nothing records. May i know why? You can try in your code sample.
Cause setAllowances is async like this.setState. so you log allowances after setAllowances it will log the old allowances.
Where in the author's allowance were they calling hooks?
l
luiz carlos batista

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

S
Sina

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


changed usestyles to mystyles but still happening the error.
Is there any documentation suggesting that is true?
yes you are right. makeStyles is hook api and you can't use that inside classes. see here
D
Djafer Abdelhadi

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


d
double-beep

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.


How did you fix it? I also use provider play console reported me that there are some bugs about hook call
F
Frank Adeleye

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)


For me it was about the redux react-redux packages not installed at project level(but present at top level in a monorepo).
J
JxDarkAngel

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

G
Gabriel Petersson

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


M
Mohamad ELnomrossie

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


This worked for me! Thanks a lot
C
Chinmay Pandey

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.


i
ishab acharya

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 !


S
Shivam Sharma

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

I had the same issue and once I found a solution I could spot your answer. Voting to raise!
A
AnatuGreen

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 ( ....
)}

F
Forest baba

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


This helped me too, I just decided to use another UI library altogether
P
Poolio

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


P
PHANTOM-X

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.


O
Orlando G Rodriguez

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.


E
Egidius

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


F
Feras

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.


P
Pavel Kalashnikov

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.


S
Salim Nadji

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.


D
Dharman

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.


E
Eden Berdugo

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

npm install react-redux

fix that


N
Nathan Gilson

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


R
Rafi Ullah

You may check your Routes. If you are using render instead of component in Route(} />) so you properly called your component in an arrow function passing proper props to that.


P
Patrik Rikama-Hinnenberg

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.


k
keegan snell

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!


M
Michael Guild

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!


I have same case, but this solution not working for me :(
A
Aindriú

My error was with the export at the end, I had the following:

https://i.stack.imgur.com/fh4TN.png

I should have removed the brackets:

https://i.stack.imgur.com/yTOfr.png