'How to remove duplicated react? (Invalid hook call)
When using libraries (I tried styledcomponents
and react-router
), an error appears in React applications:
Warning: 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 See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
After clicking on the link and reading the documentation, I decided that for some reason I have several versions of React or something like that, since after doing this point:
// Add this to node_modules/react-dom/index.js file
window.React1 = require('react');
//Add this to your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2);
//If it prints false then you might have two Reacts and need to figure out why that happened.
//This issue(https://github.com/facebook/react/issues/13991)
//includes some common reasons encountered by the community.
Here is the code:
import {BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import './index.css';
import AboutPage from './pages/aboutpage';
import BlogPage from './pages/blogPage';
require('react-dom'); //checked for duplication as written in the
window.React2 = require('react'); //documentation (see above)
console.log(window.React1 === window.React2);
function App() {
return (
<Router>
<div>
<header>
<a href = '/'>Home</a>
<a href = '/posts'>Posts</a>
<a href = '/about'>About</a>
</header>
</div>
</Router>
);
}
export default App;
The error appears right after I wrap in <Router></Router>
node_modules/react-dom/index.js (path from documentation)
'use strict';
function checkDCE() {
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
) {
return;
}
if (process.env.NODE_ENV !== 'production') {
throw new Error('^_^');
}
try {
__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
} catch (err) {
console.error(err);
}
}
if (process.env.NODE_ENV === 'production') {
checkDCE();
module.exports = require('./cjs/react-dom.production.min.js');
} else {
module.exports = require('./cjs/react-dom.development.js');
}
window.React1 = require('react'); //did as written in the documentation
I got false
. After clicking on the link with the solution from the community (https://github.com/facebook/react/issues/13991),
I honestly did not understand any of the solutions.
Maybe someone met this problem and can help me? PLEASE :(
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|