React useEffect is not triggering on route change

use the key attribute so everytime we render new component (different key)

<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />

The useEffect is not triggered because the App component is not re-rendered, nothing changed in that component (no state or props update).

If you want the App component to re-render when the route change, you can use the withRouter HOC to inject route props, like this :

import { Switch, Route, withRouter } from 'react-router-dom';

const App = () => {

  useEffect( () => console.log('Refresh'));

  return (...);
}

export default withRouter(App);

Example : https://codesandbox.io/s/youthful-pare-n8p1y


Use the 2nd argument to useEffect to conditionally apply effect. For example via react-router-dom, you get some properties

const { schoolId, classId } = props

useEffect(() => {
   // fetch something here
}, [schoolId, classId)

Here [schoolId, classId acts as the unique identifier for useEffect to trigger.


use useLocation and useLayoutEffect get more efficiency :

   import { useLocation } from "react-router-dom";
//...
   const location = useLocation();
//...
   useLayoutEffect(() => {
    console.log("location",location) 
    
   }, [location])