App.js:
import React from 'react';
import { Router, Route } from 'react-router-dom';
import Display from './Components/Display';
export function App() {
return (
<Router>
<Route path="/" component={Display} />
</Router>
);
}
Display.js
import React from 'react';
import { useLocation, useHistory } from 'react-router-dom';
function History() {
let history = useHistory(); // error saying invalid hook call
let location = useLocation();
console.log(history);
return <h2>Hello Display</h2>;
}
export default History;
I am facing invalid hook calls on using those hooks.
This is my dependencies :
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router": "^5.1.2",
"react-scripts": "3.4.1",
"redux": "^4.0.5"
}
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 .
If the error persists, try to delete your node_modules and package-lock. json (not package. json ) files, re-run npm install and restart your IDE. The error is often caused by having multiple versions of react in the same project.
Solution 9: Invalid hook call. Hooks can only be called inside of the body of a function component. When you face this issue you just need to reinstall this “npm install react-bootstrap@next [email protected]” then your error will be resolve.
Through the history object, we can access and manipulate the current state of the browser history. All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history.
In my case, I solved the issue by adding resolutions in package .json
"resolutions": {
"babel-loader": "8.1.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-router-dom": "5.3.0"
}
You are using Router component from react-router-dom without providing a custom history object.
You can either use BrowserRouter or provide a custom history prop
import React from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';
import Display from './Components/Display';
export function App() {
return (
<Router>
<Route path="/" component={Display } />
<Router>
)
}
Display.js
import React from 'react';
import { useLocation, useHistory } from 'react-router-dom'
function History() {
let history = useHistory();
let location = useLocation();
console.log(history)
return<h2>Hello Display</h2>
}
export default History
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With