Site Overlay

How to detect route changes with React Router 5 Hooks?

0

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.

 
 

1
0

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

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

function C() {
  let location = useLocation()

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

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