useHistory react-router-dom invalid hook call

Viewed 1574

I am trying to implement useHistory hook from react-router-dom and it doesn't seem to work. Throws invalid hook call

App.js

import React, { Component } from 'react';
<...>
import { Signup } from './Signup.js';
import { Login } from './Login.js';
import { Account } from './Account.js';
import { AuthProvider } from './contexts/AuthContext.js';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

class App extends Component {
    <...>

    render() {
        return(
            <>
               <...>
                <Router>
                    <AuthProvider>
                        <Switch>
                            <Route exact path="/" component={Signup} />
                            <Route path="/signup" component={Signup} />
                            <Route path="/login" component={Login} />
                            <Route path="/account" component={Account} />
                        </Switch>
                    </AuthProvider>
                </Router>
            </>
        );
    }
}

export default App;

Account.js

import React from 'react';
import { useHistory } from 'react-router-dom';

export const Account = () => {
    const history = useHistory();
    return(
        <h1>Hello...</h1>
    );
}

And it throws error on this line: const history = useHistory();

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: <...>

Latest React version, latest React Router version, also if it makes any difference I installed react-router-dom after create-react-app. Link(s) and routes itself are working without any issues. Found few topics on this here but no clear/working solution. Thank you.

3 Answers

Found a solution: previously I installed react-router-dom directly from macOS terminal and everything worked except for useHistory, however this time I installed react-router-dom directly from VS code's terminal and it seems to be working fine now. Hope this helps to anybody having this issue.

In my case the error was caused by something I couldn't find elsewhere.

Taking your example, I was using something of the likes:

<Route path="/signup" children={Signup} />
// So I changed it to
<Route path="/signup" component={Signup} />

Notice component prop in <Route />

I believe the Error was caused because component just calls the component and children appends it so I would be calling react and/or hooks twice.

If anyone knows and can explain better, feel free to do so!

I checked the package.json and noticed that I hadn't npm install react-router-dom.

Related