I get the 'Invalid hook error' using this example from Material UI's website: https://material-ui.com/styles/advanced/#GlobalCss.js
import React from 'react';
import { makeStyles } from '@material-ui/styles';
const useStyles = makeStyles({
'@global': {
'.cssjss-advanced-global-root': {
height: 100,
width: 100,
backgroundColor: 'blue',
},
'.cssjss-advanced-global-child': {
height: 8,
backgroundColor: 'red',
},
},
});
export default function GlobalCss() {
useStyles(); // <-- causes error
return (
<div className="cssjss-advanced-global-root">
<div className="cssjss-advanced-global-child" />
</div>
);
}
Material UI doesn't assign the "useStyles()" to a variable, they just call it inside the function component.
I, also need to call 'useStyles()' by itself to set global css.
Here is my package.json:
"peerDependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"@babel/core": "^7.4.4",
"@babel/plugin-proposal-class-properties": "^7.4.4",
"@babel/plugin-transform-react-jsx": "^7.3.0",
"@babel/plugin-transform-runtime": "^7.4.4",
"@babel/preset-env": "^7.4.4",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.4.4",
"@babel/runtime": "^7.4.4",
"@material-ui/core": "^3.9.3",
"@material-ui/icons": "^3.0.2",
"@material-ui/styles": "^3.0.0-alpha.10",
"babel-loader": "^8.0.5",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^2.1.1",
"css-object-loader": "0.0.7",
"node-sass": "^4.12.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
}
-------- FIXED --------
I ended up using the GlobalCss as an exported module in my component library, as suggested.
But noticed there was a duplicate "react" instance, which caused the "Invalid Hook Error".
// run this to check for multiple instances
npm ls react
Here is how I told webpack to isolate the current "react" library being used:
// webpack.config.js
resolve:{
alias: {
react: path.resolve('./node_modules/react')
}
}
That fixed the error.