Next.js Discord

Discord Forum

Error: NextRouter was not mounted.

Answered
Blue-winged Warbler posted this in #help-forum
Open in Discord
Avatar
Blue-winged WarblerOP
Hi all,

I'm encountering a runtime error stating "Unhandled Runtime Error: Error: NextRouter was not mounted" in my Header component. This error seems to occur when I try to use the useRouter hook from next/router in my component I am using for my NavBar, which is a child of Header.
Here is the snippet of my code:

"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";

const CustomMobileLink = ({ href, title, className = "", toggle }) => {
  const router = useRouter(); // this is where it is breaking
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  const handleClick = (e) => {
    e.preventDefault();
    toggle();
    if (isMounted) {
      router.push(href);
    }
  };

  return (
    <button
      href={href}
      className={`${className} relative group`}
      onClick={handleClick}
    >
      {title}
      <span
        className={`h-[0.5px] inline-block bg-dark absolute left-0 -bottom-0.5
            group-hover:w-full transition-[width] ease duration-300`}
      >
        &nbsp;
      </span>
    </button>
  );
};

export default CustomMobileLink;


Any and all help is appreciated.
Answered by Cuckoo wasp
NextJS docs are too confusing for a beginner. I believe you're using App Router. Import useRouter from next/navigation.
View full answer

3 Replies

Avatar
Cuckoo wasp
NextJS docs are too confusing for a beginner. I believe you're using App Router. Import useRouter from next/navigation.
Answer
Avatar
Blue-winged WarblerOP
This worked. Thank you so much @Cuckoo wasp !
Avatar
Cuckoo wasp
No prob. When reading docs, make sure you're in the App Router section, not Page one.