Skip to content

[WIP-FEATURE-REQUEST | v2.x]: usePreviousRoute() hook: Implement for both NextJS router and Tanstack router #3

@codesplinta

Description

@codesplinta

Feature Request

Description / Observed Behavior

There is need to implement a usePreviousRoute() hook that works with both NextJS router and Tanstack router.

Additional Context

/*import {
  useLocation
} from "react-router-dom-v5-compat";
*/
import { useLocation } from "react-router-dom"; //v6.x
import { useRouter } from "next/router";
import { useRef } from "react";

export const usePreviousRoute = () => {
  const isReactRouterDOMRouting = typeof useLocation === "function";
  const useBrowserRouter = isReactRouterDOMRouting ? useLocation : useRouter;
  const router = useBrowserRouter();

  const ref = useRef(null);

  useEffect(() => {
    () => {
       ref.current = router.key ?  router.pathname : router.asPath
     }
  }, [location.key])

  if ("on" in (router.events || {})) {
    router.events.on("routeChangeStart", () => {
      ref.current = router.asPath;
    });
  }

  return ref.current;
};

Request for busser version.

v2.0.0

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions