Last active
May 8, 2025 01:09
-
-
Save webowodev/c0e8abf5e78f36d5ea5e24cd028b3174 to your computer and use it in GitHub Desktop.
NextJS Route History Provider to prevent user go outside our app when navigate back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // on your root layout /app/layout.tsx | |
| // ... | |
| export default function RootLayout({children}: {children: React.ReactNode}) { | |
| return <RouteHistoryProvider> | |
| {children} | |
| </RouteHistoryProvider>; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // providers/routeHistory.tsx | |
| 'use client'; | |
| import { usePathname } from "next/navigation"; | |
| import { createContext, useEffect, useRef } from "react"; | |
| export type IRouteHistoryContext = { | |
| previousRoute: string | null; | |
| } | |
| export const RouteHistoryContext = createContext<IRouteHistoryContext>({} as IRouteHistoryContext); | |
| const RouteHistoryProvider = ({ children }: { children: React.ReactNode }) => { | |
| const pathname = usePathname(); | |
| const ref = useRef<string | null>(null); | |
| useEffect(() => { | |
| ref.current = pathname; | |
| }, [pathname]); | |
| return <RouteHistoryContext.Provider value={{ previousRoute: ref.current }}> | |
| {children} | |
| </RouteHistoryContext.Provider> | |
| }; | |
| export default RouteHistoryProvider; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // /hooks/use-route-history.ts | |
| import { | |
| IRouteHistoryContext, | |
| RouteHistoryContext, | |
| } from "@/providers/routeHistoryProvider"; | |
| import { useContext } from "react"; | |
| const useRouteHistory = () => { | |
| const context = useContext<IRouteHistoryContext | null>(RouteHistoryContext); | |
| return context; | |
| }; | |
| export default useRouteHistory; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment