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

55

319

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;
Drug answered 19/6, 2019 at 8:57 Comment(1)
just a note, This error appears when instead of calling component like <Component prop1={prop1} /> if its written like a function call Component(prop1) then also same error will appear. I did this mistake when converting a util function into a functional component and forgetting to change the calling line.Drucilladrucy
T
110

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;
Tale answered 19/6, 2019 at 9:13 Comment(7)
One thing want to ask you, after calling setAllowances(data), allowances should have data right? otherwise, when allowances have data?Drug
Yes. After calling setAllowances(data). setAllowances working like this.setState({allowances: data})Tale
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.Drug
Cause setAllowances is async like this.setState. so you log allowances after setAllowances it will log the old allowances.Tale
Where in the author's allowance were they calling hooks?Inurn
@Inurn It call React.useContext here github.com/mui-org/material-ui/blob/…Tale
@Inurn line-25 is where you're trying to findSublet
C
207

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.

Choppy answered 2/9, 2020 at 12:22 Comment(13)
Thanks Mate! you saved my day! All those using locally packages via npm/yarn link, follow this!Elytron
This worked for me. This was my exact issue.Tammeratammi
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. 🤔Mauldon
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.Vitrain
It took me 8 hours with this issue and trying to finish the feature in a different way. Thank you so muchKeratin
It fixed it locally. But after publishing my package, this error comes back. Anyone?Subgroup
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!Gaullism
To complete this answer, check this link about this in the react repository github.com/facebook/react/issues/14257#issuecomment-809702813Gutturalize
Try npm ls react which would list all the React versions and make sure to remove all the duplicate versions of React or link to a specific version.Maurilia
Using npm version 9.5.0, node version 18.14.2, and react version 18.2.0: I am getting the error Cannot set properties of null (setting 'dev') when I try to link the react package. Relevant github issue here.Incompletion
I had to do the same for react-router-dom, and @emotion/react, in addition to react to finally get everything to work.Disadvantage
While npm ls react/yarn why react turned up exactly the results I expected, I DID NOT expect that tsup was bundling react! I switched our internal deps built with tsup to tsup-node and solved my problem! Obscure I know - but I had to tell someone! I spent multiple days on this - trying to debug storybook. Once I gave up I figured this out while debugging chunking with vite.Mansur
Thanks for saving me from going crazy. My case was similar: I had my package.json point to a local dir to test a library package. Needed to delete the package's dependencies installed by npm (e.g. node_modules/mylib/node_modules)Six
T
110

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;
Tale answered 19/6, 2019 at 9:13 Comment(7)
One thing want to ask you, after calling setAllowances(data), allowances should have data right? otherwise, when allowances have data?Drug
Yes. After calling setAllowances(data). setAllowances working like this.setState({allowances: data})Tale
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.Drug
Cause setAllowances is async like this.setState. so you log allowances after setAllowances it will log the old allowances.Tale
Where in the author's allowance were they calling hooks?Inurn
@Inurn It call React.useContext here github.com/mui-org/material-ui/blob/…Tale
@Inurn line-25 is where you're trying to findSublet
S
35

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} />
    )
}
Salman answered 27/5, 2020 at 17:21 Comment(0)
H
25

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

Hollerman answered 24/7, 2020 at 17:1 Comment(0)
M
13

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.

Mirk answered 14/1, 2020 at 16:32 Comment(1)
How did you fix it? I also use provider play console reported me that there are some bugs about hook callBlowzed
H
12

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

Hjerpe answered 19/6, 2019 at 9:5 Comment(4)
changed usestyles to mystyles but still happening the error.Drug
Is there any documentation suggesting that is true?Minority
yes you are right. makeStyles is hook api and you can't use that inside classes. see hereHjerpe
This change solved the problem for me. I changed const useStyles = ... to const jssStyles = ...Harriot
W
12

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

Welles answered 16/5, 2021 at 12:44 Comment(0)
T
10

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)

Thole answered 8/10, 2020 at 16:13 Comment(2)
For me it was about the redux react-redux packages not installed at project level(but present at top level in a monorepo).Circumsolar
I had idiot error. :| But I still post here (quite negociate yours). I put "dispatch = useDispatch();" out side of class then error happen without details place bug. Until I saw your answer and re-check again then bug resolved.Amand
L
9

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>
        }
      />
Lorylose answered 17/6, 2021 at 16:58 Comment(0)
U
6

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);
Unbelievable answered 22/10, 2020 at 21:57 Comment(0)
S
6

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

Swellfish answered 12/2, 2021 at 12:34 Comment(0)
T
5

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 !

Tableau answered 1/4, 2020 at 9:28 Comment(0)
F
4

enter image description here

In my Next.js app, I encountered the same issue. In my case, I believe it was a cache-related problem. Running the project after removing the ".next" folder resolved the issue. I hope that removing the build folder in React will have the same effect.

Fornix answered 9/7, 2022 at 14:58 Comment(0)
I
4

Happens to me when I used to call useNavigate() on a certain function upon onClick.

Immediacy answered 6/3, 2023 at 8:40 Comment(0)
M
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.

Mort answered 19/6, 2019 at 11:7 Comment(0)
I
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 ( ....
)}
Imprecise answered 1/1, 2022 at 18:48 Comment(0)
D
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

Dorothi answered 30/8, 2020 at 16:46 Comment(1)
This helped me too, I just decided to use another UI library altogetherCoadjutant
B
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

Boutique answered 7/5, 2021 at 13:35 Comment(0)
R
2

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.

Reviere answered 6/6, 2021 at 18:23 Comment(1)
Kind of similar to this, my problem was that I had added "react" as a dependency in my npm workspace AND the root project, leading to multiple versions of react getting installed (albeit in different node_modules folders). Removing that entry from my workspace package.json and rerunning npm i resolved the problem for me.Leshalesher
B
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.

Borgerhout answered 29/6, 2021 at 3:19 Comment(0)
H
2

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

Hathor answered 12/8, 2021 at 17:1 Comment(0)
N
2

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.

Nylons answered 16/8, 2021 at 15:35 Comment(0)
B
2

Be aware 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 from same folder like 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.

Bullhead answered 16/8, 2021 at 16:39 Comment(0)
N
2

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!

Nutpick answered 23/1, 2022 at 16:37 Comment(0)
S
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.

Swing answered 28/1, 2022 at 19:14 Comment(0)
G
2

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!

Gaullism answered 17/2, 2022 at 20:15 Comment(1)
I have same case, but this solution not working for me :(Allophone
T
2

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

Talich answered 29/3, 2022 at 10:12 Comment(0)
C
2

In my case, I was using navigation in App.js where I have Stack Navigator & assigning all my screens. Please remove below line if you have that.

const navigation = useNavigation()
Cognition answered 3/8, 2022 at 6:30 Comment(0)
S
2

There are many reasons for this to happen. One of which is , when the installation of the packages are done out of scope. It tends to get confused between two react apps.

Explanation:

The packages shouldn't be installed in different levels.

The mistake

app
 |node_modules          <-- some packages installed here
 |package.json
node_modules
package.json            <-- some packages installed here

Correct Way

app
 |node_modules
 |package.json          <-- install all the packages at the same heirarchy
Scrapbook answered 3/11, 2022 at 7:13 Comment(0)
O
2

with NPM npm install react@latest react-dom@latest with YARN yarn add react@latest react-dom@latest

Orthostichy answered 24/11, 2022 at 20:52 Comment(0)
A
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.

Ankney answered 12/5, 2020 at 23:8 Comment(0)
C
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.

Cassation answered 16/7, 2020 at 7:13 Comment(0)
U
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.

Unorthodox answered 3/2, 2021 at 15:8 Comment(0)
M
1

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

Maelstrom answered 16/5, 2021 at 13:17 Comment(1)
Khaled Rakhisi, a link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.Dally
H
1

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

npm install react-redux

fix that

Homburg answered 7/8, 2021 at 10:55 Comment(0)
B
1

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

Buster answered 9/4, 2022 at 9:34 Comment(0)
B
1

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.
Bouleversement answered 13/4, 2022 at 15:59 Comment(0)
S
1

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.

Sized answered 4/6, 2022 at 18:26 Comment(0)
G
0

I had same problem while I use useLocation hook in class component

Error:

import React from "react";
import { useLocation } from "react-router-dom";

class ShowTheLocation extends React.Component {
  const location = useLocation();
  render() {
    return <div>You are now at {location.pathname}</div>;
  }
}

Solution: I have converted class component to function component then issue resolved

import React from "react";
import { useLocation } from "react-router-dom";

const ShowTheLocation = () => {
  const location = useLocation();

  return <div>You are now at {location.pathname}</div>;
}
Groveman answered 22/6, 2022 at 6:35 Comment(0)
M
0

Bad:

import { useDispatch } from 'react';

Good:

import { useDispatch } from 'react-redux';

I remember It happened to me once that I imported useDispatch from ‘react’ as opposed to import it from ‘react-redux’ It was very difficult to figure out, because code seamed right from every angle, I just could not guess it for hours lol

Maidenhead answered 22/6, 2022 at 17:13 Comment(0)
C
0

I'm using Electron. I tested all the answers above, even stripping down to the base app, and found it was still happening.

Turns out if you are using electron (specifically expo-electron, in my case), it has it's own webpack configuration, and you need to white-list redux in the webpack config. My electron-webpack.js file looks like this:

const { withExpoAdapter } = require("@expo/electron-adapter");

// Provide any overrides for electron-webpack: https://github.com/electron-userland/electron-webpack/blob/master/docs/en/configuration.md
module.exports = withExpoAdapter({
  projectRoot: __dirname,
  whiteListedModules: ["react-redux"],
});
Cis answered 23/7, 2022 at 14:50 Comment(0)
D
0

For me this issue was caused by the webpack setting resolve.symlinks (https://webpack.js.org/configuration/resolve/#resolvesymlinks), which was set to false:

  resolve: {
    symlinks: false,

Because of this the symlink to React from another package couldn't be resolved and caused the Invalid Hook Call error.

Setting it to true or simply omitting it (apparently it defaults to true) solved the problem:

  resolve: {
    symlinks: true,
Deciare answered 18/10, 2022 at 11:0 Comment(0)
B
0

I had the same issue, and it got resolved after editing launch.json file for vscode and changing the configurations type by removing 'pwa-' from the type:

So, instead of:

"type": "pwa-node",

It should be:

"type": "node",
Barbabra answered 8/11, 2022 at 14:47 Comment(0)
A
0

In my case, it's come from the Chrome Extension: Loom. But it can come from any extension written via React. Crazy world, isn't it? Just disable the extension resolves the error.

Adjective answered 9/3, 2023 at 18:4 Comment(0)
G
0

In mycase i have used useCallback hook inside class component due to this i had a error mentioned in the question

Error:

import React, { useCallback } from 'react'
import { FormControlLabel, Switch, withStyles } from '@material-ui/core'


const styles = {
    root: {
        alignItems: 'center',
        display: 'flex',
        height: '50px',
        justifyContent: 'center',
        padding: 0,
        width: '90px',
    },
    switchBase: {
        '& + $track': {
            backgroundColor: 'lightblue',
        },
        '&$checked': {
            color: 'lightblue',
            transform: 'translateX(40px)',
        },
    },
    thumb: {
        borderRadius: '0px',
        height: '15px',
        marginTop: '8px',
        transform: 'translateX(19px)',
        width: '15px',
    },
    track: {
        borderRadius: '0px',
        height: '20px',
        width: '40px',
    },
}

class SwitchLabels extends React.Component {
    state = {
        checked: false,
    }

    handleChange = React.usecallback(event => { // here i have used useCallback hook
        this.props.changeStatus(event.target.checked)
        this.setState({ checked: event.target.checked })
    }, [])

    render() {
        return (
            <FormControlLabel
                control={
                    <Switch
                        classes={this.props.classes}
                        checked={this.state.checked}
                        onChange={this.handleChange}
                        disableElevation
                        disableRipple
                        style={{ backgroundColor: 'transparent' }}
                        value={this.state.checked}
                        color='primary'
                    />
                }
                labelPlacement='start'
                label={'Show inactive'}
            />
        )
    }
}

export default withStyles(styles)(SwitchLabels)

Solution:

import React from 'react'
import { FormControlLabel, Switch, withStyles } from '@material-ui/core'


const styles = {
    root: {
        alignItems: 'center',
        display: 'flex',
        height: '50px',
        justifyContent: 'center',
        padding: 0,
        width: '90px',
    },
    switchBase: {
        '& + $track': {
            backgroundColor: 'lightblue',
        },
        '&$checked': {
            color: 'lightblue',
            transform: 'translateX(40px)',
        },
    },
    thumb: {
        borderRadius: '0px',
        height: '15px',
        marginTop: '8px',
        transform: 'translateX(19px)',
        width: '15px',
    },
    track: {
        borderRadius: '0px',
        height: '20px',
        width: '40px',
    },
}

class SwitchLabels extends React.Component {
    state = {
        checked: false,
    }

    handleChange = event => { // after removing useCallback working fine
        this.props.changeStatus(event.target.checked)
        this.setState({ checked: event.target.checked })
    }

    render() {
        return (
            <FormControlLabel
                control={
                    <Switch
                        classes={this.props.classes}
                        checked={this.state.checked}
                        onChange={this.handleChange}
                        disableElevation
                        disableRipple
                        style={{ backgroundColor: 'transparent' }}
                        value={this.state.checked}
                        color='primary'
                    />
                }
                labelPlacement='start'
                label={'Show inactive'}
            />
        )
    }
}

export default withStyles(styles)(SwitchLabels)
Groveman answered 12/3, 2023 at 2:8 Comment(0)
M
0

This occured for me when improperly destructuring the response from an axios.get server call. I changed:

const { retrievedUser } = await axios.get('www.mysite.com/user/userid')

to:

const { data: retrievedUser } = await axios.get('www.mysite.com/user/userid')
Manifold answered 13/4, 2023 at 20:0 Comment(0)
H
0

This might also occur because your hook is called below any asynchronous or nested functions. You need to move the hook to the top level of the function body.

In your case, it looks like you're using a hook for class component. Consider changing the class component to a function component and then using the hook inside the top-level of the function component.

Humber answered 26/5, 2023 at 6:56 Comment(0)
B
0

For those who have a Monorepo setup (whether it's multiple React projects or a combination of React and React Native):

I encountered an error after updating my React Native project to RN 70 and React 18 while executing the app via the Metro bundler:

1- Ensure a unified version of react, react-dom, and react-redux is used across all packages.

2- (ignore if you don't have a react native package) Verify that both react and react-redux aren't hoisted for the mobile (React Native package). This means both packages should be present in the node_modules directory of the mobile package. Learn more about nohoist here.

A useful tip:

yarn why react

This command displays which packages have react as a dependency. Additionally:

yarn list react

This command presents the versions of react in your project. Ideally, there should only be one version.

The same applies for react-redux and react-thunk.

Benzedrine answered 25/7, 2023 at 22:16 Comment(0)
C
0

I was using microfrontend architecture. The problem was that the react dependencies were not shared during the compilation in Webpack.

Example nx config:

module.exports = {
  name: 'mfe',
  remotes: ['mfe-remote'],
  additionalShared: ['react', 'react-dom', /* 'any-react-library' used by both module */],
}
Chadd answered 6/10, 2023 at 15:52 Comment(0)
H
0

In my case, I called the functional component as a function myComponent() instead of using it as a component, i.e. <myComponent />, and that solved my issue.

Heartfelt answered 18/11, 2023 at 19:22 Comment(0)
M
0

In my case , the issues was because somehow , I was generating two react trees because I had two ReactDOM.render calls . One in index.js and other one in a component. Error goes away , after I removed one of the ReactDOM.render call like this

export const RenderTopMenuResultPage = (props) => {

    ReactDOM.render(    
        <CreateTopMenuResultPage />, 
        document.getElementById('result-page-sort-menu')
    )
} 

to

export const RenderTopMenuResultPage = (props) => {
    return <CreateTopMenuResultPage />;
};
Molokai answered 20/11, 2023 at 16:43 Comment(0)
R
0

We have encountered an issue with folder linking through yarn where yarn fails to remove the links completely. This problem arose while working with the React Map Library build, and it looks like what's shown in the screenshot.

To fix this build error, follow these steps:

Run yarn unlink react && yarn unlink react-dom, and your other libraries. Ideally, this command should remove all linked library folders. You can also use the command yarn unlink --all. Next, delete the node_modules folder in all linked repositories.

IMPORTANT!!! If rebuilding the dev server and relinking didn't solve the issue, it's possible that Yarn didn't completely clean up the links. You can manually delete them with the command rm -rf ~/.config/yarn/link/*. Then, relink the necessary folders (react, react-dom), and everything should work again. Hope this helps!

Redletter answered 8/4 at 12:41 Comment(0)
S
-2

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);
    }
};
Seeseebeck answered 11/9, 2020 at 6:49 Comment(0)
H
-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.

Hrvatska answered 21/5, 2021 at 10:22 Comment(1)
sounds like you need to setup peer dependencies in your package.json nodejs.org/es/blog/npm/peer-dependenciesGaullism
O
-4

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

Outbreed answered 7/9, 2021 at 6:4 Comment(1)
This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question.Ahq

© 2022 - 2024 — McMap. All rights reserved.