Define the context:
'use client';
import { useContext, useEffect, useState, createContext } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
export const useNavigationContext = () => useContext(NavigationContext);
export const NavigationProvider = ({ children }: { children: React.ReactNode }) => {
const navigation = useNavigation();
return <NavigationContext.Provider value={navigation}>{children}</NavigationContext.Provider>;
};
const useNavigation = () => {
const pathname = usePathname();
const searchParams = useSearchParams();
const [currentRoute, setCurrentRoute] = useState<string | null>(null);
const [previousRoute, setPreviousRoute] = useState<string | null>(null);
useEffect(() => {
const url = `${pathname}?${searchParams}`;
setPreviousRoute(currentRoute);
setCurrentRoute(url);
}, [pathname, searchParams]);
return { previousRoute };
};
const NavigationContext = createContext<ReturnType<typeof useNavigation>>({
previousRoute: null,
});
Use Provider in RootLayout:
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<NavigationProvider>
{children}
</NavigationProvider>
</body>
</html>
);
}
Consume in Client Component:
'use client';
import Link from 'next/link';
import { useNavigationContext } from '@/contexts';
const BackButton = () => {
const { previousRoute } = useNavigationContext();
return <Link href={previousRoute ?? '/'}>Go back</Link>;
};
export default BackButton;