285

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;
Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
lwin
  • 3,784
  • 6
  • 25
  • 46

51 Answers51

182

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.

syntax-punk
  • 3,736
  • 3
  • 25
  • 33
  • 20
    Thanks Mate! you saved my day! All those using locally packages via npm/yarn link, follow this! – waleed ali Nov 20 '20 at 13:05
  • 6
    This worked for me. This was my exact issue. – Wil Jan 27 '21 at 21:17
  • 2
    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. – Pouya Jabbarisani Feb 21 '21 at 11:50
  • 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. – fabienbranchel Feb 25 '21 at 10:10
  • 3
    It took me 8 hours with this issue and trying to finish the feature in a different way. Thank you so much – Bishoy Melek Jun 02 '21 at 23:21
  • It fixed it locally. But after publishing my package, this error comes back. Anyone? – Nadar Jun 20 '21 at 09:20
  • 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 `, and then start the project. Fixed everything! – Michael Guild Feb 17 '22 at 15:50
  • 1
    To complete this answer, check this link about this in the react repository https://github.com/facebook/react/issues/14257#issuecomment-809702813 – Albert Hidalgo May 31 '22 at 20:05
  • 4
    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. – Kuldeep Saxena Sep 04 '22 at 18:14
  • 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](https://github.com/npm/cli/issues/4064#issuecomment-1471742150). – somethingRandom Apr 06 '23 at 11:11
  • I had to do the same for `react-router-dom`, and `@emotion/react`, in addition to `react` to finally get everything to work. – cyclingLinguist May 15 '23 at 19:09
  • 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. – kross Jun 23 '23 at 00:04
104

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;
Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
Giang Le
  • 6,446
  • 4
  • 23
  • 26
  • 2
    One thing want to ask you, after calling setAllowances(data), allowances should have data right? otherwise, when allowances have data? – lwin Jun 19 '19 at 10:13
  • Yes. After calling setAllowances(data). `setAllowances` working like `this.setState({allowances: data})` – Giang Le Jun 19 '19 at 10:21
  • 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. – lwin Jun 19 '19 at 10:26
  • Cause `setAllowances` is async like this.setState. so you log `allowances` after `setAllowances` it will log the `old allowances`. – Giang Le Jun 19 '19 at 10:41
  • 1
    Where in the author's allowance were they calling hooks? – Thuy Oct 10 '21 at 04:44
  • @Thuy It call `React.useContext` here https://github.com/mui-org/material-ui/blob/2296d56b259cfb7dd14da89045162a1cd02c1c10/packages/mui-styles/src/makeStyles/makeStyles.js#L204 – Giang Le Oct 10 '21 at 07:34
33

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

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

11

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

Sina
  • 1,055
  • 11
  • 24
11

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Zelda Yuan
  • 111
  • 1
  • 2
11

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

9

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)

Frank Adeleye
  • 91
  • 1
  • 2
  • For me it was about the `redux` `react-redux` packages not installed at project level(but present at top level in a monorepo). – Udayraj Deshmukh Sep 10 '21 at 20:00
  • 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. – Thang Pham Mar 15 '23 at 09:26
7

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>
        }
      />
Shivam Sharma
  • 1,277
  • 15
  • 31
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);
JxDarkAngel
  • 911
  • 11
  • 4
4

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 !

Redmen Ishab
  • 2,199
  • 18
  • 22
4

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

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41
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.

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 ( ....
)}
AnatuGreen
  • 579
  • 7
  • 14
3

enter image description here

In my NextJs app, I got the same issue. In my case, I think it was a cache-related issue. Run the project after removing the ".next" folder fixed the issue. I hope removing the build folder in React will do the same.

Lojith Vinsuka
  • 906
  • 1
  • 10
  • 8
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

forestbaba
  • 189
  • 1
  • 4
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

Poolio
  • 21
  • 2
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.

PHANTOM-X
  • 502
  • 6
  • 16
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.

Patrik Rikama-Hinnenberg
  • 1,362
  • 1
  • 16
  • 27
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!

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.

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

Egidius
  • 971
  • 1
  • 10
  • 22
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()
Muhammad Talha
  • 719
  • 1
  • 4
  • 9
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
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
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.

0xFK
  • 2,433
  • 32
  • 24
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.

Pavel Kalashnikov
  • 2,092
  • 1
  • 19
  • 22
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.

Salim Nadji
  • 715
  • 5
  • 5
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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
EdwardF
  • 75
  • 1
  • 7
1

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

npm install react-redux

fix that

Eden Berdugo
  • 179
  • 1
  • 5
1

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

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.

Rafi Ullah
  • 11
  • 1
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!

Michael Guild
  • 808
  • 9
  • 8
1

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

1

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

Justin Herrera
  • 526
  • 4
  • 11
0

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

Hadi Mir
  • 4,497
  • 2
  • 29
  • 31
Khaled Rakhisi
  • 317
  • 1
  • 4
  • 18
  • Khaled Rakhisi, a link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) 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.](/help/deleted-answers) – 4b0 May 16 '21 at 13:30
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

Aindriú
  • 3,560
  • 9
  • 36
  • 54
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.
Ruby Nanthagopal
  • 596
  • 1
  • 5
  • 17
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.

Saurabh
  • 336
  • 3
  • 9
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>;
}
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
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

Adrian
  • 122
  • 8
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"],
});
Julian K
  • 1,877
  • 2
  • 19
  • 27
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,
Johan Maes
  • 1,161
  • 13
  • 13
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",
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.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
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)
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
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')
Philip Sopher
  • 627
  • 2
  • 8
  • 19
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.

Haneen Mahdin
  • 1,000
  • 1
  • 7
  • 13
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.

-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);
    }
};
FlipNovid
  • 1,191
  • 3
  • 12
  • 20
-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.

yusha
  • 1
  • sounds like you need to setup `peer dependencies` in your package.json https://nodejs.org/es/blog/npm/peer-dependencies/ – Michael Guild Feb 16 '22 at 22:52
-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.

  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. – Noam Yizraeli Sep 07 '21 at 11:52