Search code examples
javascriptreactjsreact-hooksreact-router-dom

Syntax error: does not provide an export named 'useHistory'


I'm trying to use useHistory hook to protect the routes in the ReactJs Vite app, but receiving an error:

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/react-router-dom.js?v=6b9126db' does not provide an export named 'useHistory'

I use JWT for login in and save the token in the localStorage.

This is my code:

import { useHistory } from "react-router-dom";

export default function AdminNews() {

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (!token) {
      history.push("/login");
  }}, [history]);

  //rest of the code 
}

Solution

  • If you are using React-Router-DOM v6 then the useHistory hook was replaced by the useNavigate hook.

    import { useNavigate } from "react-router-dom";
    
    export default function AdminNews() {
      const navigate = useNavigate();
    
      useEffect(() => {
        const token = localStorage.getItem("token");
        if (!token) {
          navigate("/login");
      }}, [navigate]);
    
      //rest of the code 
    }
    

    RRDv6 has a lot of breaking changes from v4/5 so you may want to review the Main Concepts and Migration Guide for complete details.

    If you did not intend to install RRDv6 then you can revert back to v5.

    • npm uninstall react-router-dom
    • npm install react-router-dom@5 and restart app