Site Overlay

How to detect route changes with React Router 5 Hooks?


React Router 5 Hooks enable clean use of the routing features in React components, how to detect if a route change occurs and call a function when that happens.



Thanks to React Hooks, this can be easily implemented as follows:

import { Switch, useLocation } from 'react-router'

function C() {
  let location = useLocation()

    () => {
          const { pathname } = location;
          console.log('Path changed to ', pathname);

We pass location as the second argument of useEffect to re-run the code in the body if location changes.