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

JavascriptReactjsReact HooksMaterial Ui

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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;

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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)

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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.

Solution 12 - Javascript

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 !

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Solution 15 - Javascript

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

Solution 16 - Javascript

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: https://stackoverflow.com/questions/55726218/react-hooks-mobx-invalid-hook-call-hooks-can-only-be-called-inside-of-the-body

Solution 17 - Javascript

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.

Solution 18 - Javascript

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.

Solution 19 - Javascript

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.

Solution 20 - Javascript

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.

Solution 21 - Javascript

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.

Solution 22 - Javascript

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.

Solution 23 - Javascript

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

npm install react-redux

fix that

Solution 24 - Javascript

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

Solution 25 - Javascript

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.

Solution 26 - Javascript

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.

Solution 27 - Javascript

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!

Solution 28 - Javascript

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!

Solution 29 - Javascript

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

Solution 30 - Javascript

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

Solution 31 - Javascript

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.

Solution 32 - Javascript

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

Solution 33 - Javascript

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

Solution 34 - Javascript

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.

Solution 35 - Javascript

When you face this issue you just need to reinstall this "npm install react-bootstrap@next [email protected]" then your error will be resolve.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlwinView Question on Stackoverflow
Solution 1 - JavascripttheVoogieView Answer on Stackoverflow
Solution 2 - JavascriptGiang LeView Answer on Stackoverflow
Solution 3 - Javascriptluiz carlos batistaView Answer on Stackoverflow
Solution 4 - JavascriptSinaView Answer on Stackoverflow
Solution 5 - JavascriptDjafer AbdelhadiView Answer on Stackoverflow
Solution 6 - JavascriptZelda YuanView Answer on Stackoverflow
Solution 7 - JavascriptFrank AdeleyeView Answer on Stackoverflow
Solution 8 - JavascriptJxDarkAngelView Answer on Stackoverflow
Solution 9 - JavascriptGabriel PeterssonView Answer on Stackoverflow
Solution 10 - JavascriptMohamad ELnomrossieView Answer on Stackoverflow
Solution 11 - JavascriptChinmay PandeyView Answer on Stackoverflow
Solution 12 - Javascriptishab acharyaView Answer on Stackoverflow
Solution 13 - JavascriptShivam SharmaView Answer on Stackoverflow
Solution 14 - JavascriptAnatuGreenView Answer on Stackoverflow
Solution 15 - JavascriptForest babaView Answer on Stackoverflow
Solution 16 - JavascriptPoolioView Answer on Stackoverflow
Solution 17 - JavascriptBUND-XView Answer on Stackoverflow
Solution 18 - JavascriptOrlando G RodriguezView Answer on Stackoverflow
Solution 19 - JavascriptFerasView Answer on Stackoverflow
Solution 20 - JavascriptPavel KalashnikovView Answer on Stackoverflow
Solution 21 - JavascriptSalim NadjiView Answer on Stackoverflow
Solution 22 - JavascriptEdwardFView Answer on Stackoverflow
Solution 23 - JavascriptEden BerdugoView Answer on Stackoverflow
Solution 24 - JavascriptNathan GilsonView Answer on Stackoverflow
Solution 25 - JavascriptRafi UllahView Answer on Stackoverflow
Solution 26 - JavascriptPatrik Rikama-HinnenbergView Answer on Stackoverflow
Solution 27 - Javascriptkeegan snellView Answer on Stackoverflow
Solution 28 - JavascriptMichael GuildView Answer on Stackoverflow
Solution 29 - JavascriptEgidiusView Answer on Stackoverflow
Solution 30 - JavascriptAindriúView Answer on Stackoverflow
Solution 31 - JavascriptThanarubyView Answer on Stackoverflow
Solution 32 - JavascriptFlipNovidView Answer on Stackoverflow
Solution 33 - JavascriptKhaled RakhisiView Answer on Stackoverflow
Solution 34 - JavascriptyushaView Answer on Stackoverflow
Solution 35 - Javascriptkarishma tejwaniView Answer on Stackoverflow