To get the last visited page URL in React, you can use the useNavigate and useLocation hooks (for React Router v6). Here's how to implement it:
For React Router v6:
import React, { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
function MyComponent() {
const location = useLocation();
const lastVisitedUrl = useRef('');
useEffect(() => {
console.log('Last visited URL:', lastVisitedUrl.current);
lastVisitedUrl.current = location.pathname; // Update the last visited URL
}, [location]);
return <div>Check the console for the last visited URL.</div>;
}
export default MyComponent;