HomeToolsAbout

Location

useLocation

The useLocation hook returns the location object that represents the current URL.

  • You can think about it like a useState that returns a new location whenever the URL changes

This 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 );
AboutContact