'TypeError: Object(...) is not a function when using useHistory() hooks

i have an onClick event on a button that pushes requests to a server and should go back to the homepage afetr submitting , i tried to use the Reactjs useHistory hooks on that component ,however i keep getting the error TypeError: Object(...) is not a function.

I need help to get around it



Solution 1:[1]

Are you using react-router: 5.1.0? useHistory and other hooks didn't become available until then. I was getting the same error as OP using the simplest implementation and then realized I was only on react-router: 5.0.0

Solution 2:[2]

Not sure if you are only using the react library but useHistory is part of react-router library. https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md

If adding the react-router not fix the issue. Please add some code so we can help.

Solution 3:[3]

I was getting error -

TypeError: Object(...) is not a function

Solution - Looks like usehistory was deprecated for react-router-dom v6 and up. Instead try using useNavigate

Example -

import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')

Docs - You can view the official docs here from react-router

Solution 4:[4]

You can see this error

TypeError: Object(…) is not a function

when using useHistory() hooks in React class. You are not supposed to do it. Instead you are better to use the withRouter high-order component for class or context API, see link.The basic example is like this:

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

class MyClass extends React.Component {
  ...

  handleEvents = (e) => this.props.history.push('another-route')

  render(){
    return <div onClick={e => handleEvents(e)}>Hello World!</div>
  }
}

const MyClassWithRouter = withRouter(MyClass)
export MyClassWithRouter 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lounge9
Solution 2 mgiatti
Solution 3 Noah Franco
Solution 4