Skip to content
Discussion options

You must be logged in to vote

No

it's not recommended to use React Router DOM in Next.js. Use Next.js useRouter and AbortController to stop API calls during navigation.

Stop API Calls on Navigation in Next.js

  • useRouter: Detects route changes.
  • AbortController: Cancels API calls when navigation starts.
  • Cleanup Function: Removes the event listener when the component unmounts.

Code Example

import { useEffect } from "react";
import { useRouter } from "next/router";

export default function Page() {
  const router = useRouter();

  useEffect(() => {
    const controller = new AbortController();
    const handleRouteChange = () => controller.abort();

    router.events.on("routeChangeStart", handleRouteChange);
    return () 

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by MuhammadAzeemShoukat077
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants