Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function (React.js)

Viewed 2464

I use React Router Version 6 then I ran this code below:

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

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

But I got this error:

Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function

Are there any mistakes for my code?

1 Answers

For React Router Version 6, use "useNavigate" instead of "useHistory" which is React Router Version 5.

So replace your code (React Router Version 5):

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

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

With this code (React Router Version 6):

import { useNavigate } from 'react-router-dom'

function Test() {
  const navigate = useNavigate();
  navigate('/');                    // Equivalent to "history.push('/');"
  navigate('/', { replace: true }); // Equivalent to "history.replace('/');"
  navigate(-1);                     // Equivalent to "history.goBack();"
}

Test();
Related