The useLocation hook in React Router provides real-time access to the current URL information, including:
pathname (e.g., /dashboard)
search (query string like ?id=123)
hash (e.g., #settings)
state (data passed during navigation)
It automatically updates when the URL changes.
Effective Uses:
Track Page Changes
const { pathname } = useLocation();
useEffect(() => {
console.log("Current page:", pathname); // Log route changes
}, [pathname]);
Read Query Parameters
const { search } = useLocation();
const id = new URLSearchParams(search).get("id"); // Gets "123" from ?id=123
Access Hidden Navigation Data
<Link to="/profile" state={{ user: "John" }}>Profile</Link>
const { state } = useLocation();
console.log(state.user); // "John"