'Invalid hook call error when wrapping MuiThemeProvider within App
I get the following error when I wrap MuiThemeProvider in App.js. The page will not load at all. I've used it similarly in other projects, so not sure why this is happening.
react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
App.js
import React from 'react'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Home from './views/Home'
import ProjectDetailsForm from './components/ProjectDetailsForm/ProjectDetailsForm'
import { MuiThemeProvider } from '@material-ui/core/styles'
import theme from './styles/theme'
function App() {
return (
<MuiThemeProvider theme={theme}>
<Router>
<div className="app">
<Routes>
<Route
path="/"
element={[
<Home key="1"></Home>,
<ProjectDetailsForm key="2"></ProjectDetailsForm>
]}></Route>
</Routes>
</div>
</Router>
</MuiThemeProvider>
)
}
export default App
theme.js
// import { common } from '@material-ui/core/colors'
import { createTheme } from '@material-ui/core/styles'
// import { black } from '@mui/material/colors'
const theme = createTheme({
components: {
MuiFormLabel: {
styleOverrides: {
root: {
color: '#000'
}
}
},
MuiInputLabel: {
styleOverrides: {
root: {
color: '#000'
}
}
}
}
})
export default theme
Solution 1:[1]
This issue can happen when you're React tries to load twice. For example, if I make my own library that uses React, and then import it locally into a project that also uses React. What's in this file ./components/ProjectDetailsForm/ProjectDetailsForm'?
Solution 2:[2]
Solved:
I realized I hadn't yet installed @material-ui/core. Once I tried, I was getting 'could not resolve dependency errors'. Had to use legacy MUI dependencies due to conflicts with React 18.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | P Savva |
| Solution 2 | ju_ro |
