devtom
devtom

Reputation: 101

useHistory react-router-dom invalid hook call

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.

Upvotes: 5

Views: 1956

Answers (3)

agelgel
agelgel

Reputation: 51

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

Upvotes: 0

juanmartin
juanmartin

Reputation: 113

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!

Upvotes: 1

devtom
devtom

Reputation: 101

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.

Upvotes: 5

Related Questions