Error: Invalid hook call, React router history

Hi guys, I’m a react beginner and I tried to execute a function to logout, but I get this error. I think the error is related to the useHistory function because if I remove it, everything works perfectly.
Or in any case, someone knows how to redirect to another page programmatically

Error: Invalid hook call. Hooks can only be called inside of the body of a function component

This is my code.

import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import token from '../services/token'
import api from '../services/api'
import { useHistory } from 'react-router-dom';

const noLogueado = <React.Fragment>
    <li className="nav-item">
        <Link className="nav-link" to="/login">Login</Link>
    <li className="nav-item">
        <Link className="nav-link" to="/register">Registrarse</Link>

const logueado = <li className="nav-item dropdown">
    <a className="nav-link dropdown-toggle" href="#" role="button" id="dropdownPerfil" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

    <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownPerfil">
        <a className="dropdown-item" href="#">Mi Perfil</a>
        <a className="dropdown-item" href="#" onClick={() => Logout()}>Cerrar sesión</a>

const Logout = () => {
    let history = useHistory();"logout", "").then(
        (data) => {
            // token.remove();
        (error) => {
            // token.remove();

export class NavBar extends Component {
    render() {
        return (
            <nav className="navbar navbar-expand navbar-dark bg-dark">
                <Link className="navbar-brand" to="/">
                <div className="collapse navbar-collapse">
                    <ul className="navbar-nav ml-auto">
                            token.isValid() ? logueado : noLogueado

export default NavBar

62 thoughts on “Error: Invalid hook call, React router history”

Leave a Comment