useLocation
The useLocation
hook returns the location
object that represents the current URL.
useState
that returns a new location whenever the URL changesThis could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads, as in the following example:
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router, Switch, useLocation } from "react-router-dom"; function usePageViews() { const location = useLocation(); React.useEffect(() => { ga.send(["pageview", location.pathname]); }, [location]); } function App() { usePageViews(); return <Switch>...</Switch>; } ReactDOM.render( <Router> <App /> </Router>, node );