Search code examples
reactjsreact-hooksmernreact-dom

Why I'm getting this Error: Invalid hook call. Hooks can only be called inside of the body of a function component/


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

This is my App.js code

import './App.css';
import Header from './Header'
function App() {
  return (
    <div className="app">
      < Header />

    </div>
  );
}
export default App;

Header.js code

import React from 'react'
import './Header.css';
import PersonIcon from '@material-ui/icons/Person';
import IconButton from '@material-ui/core/IconButton';


function Header() {

    return (    
        <div className='header'>
            <IconButton>
                <PersonIcon fontSize="large" className="header__icon" />
            </IconButton>
        </div>
    )
}
export default Header

I used my App.js in index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

When I remove <PersonIcon> and <IconButton> tags code works fine.


Solution

  • Try this

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

    Then

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

    Restart the React server

    npm start
    // OR
    yarn start
    

    Let me know if it works, Good Luck