Sometimes, we want to detect route change with React Router.
In this article, we’ll look at how to detect route change with React Router.
How to detect route change with React Router?
To detect route change with React Router, we can use the useLocation
hook.
For instance, we write
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SomeComponent = () => {
const location = useLocation();
useEffect(() => {
console.log("Location changed");
}, [location]);
//...
};
to call useLocation
to return the location
object.
Then we listen for changes to the location
object with the useEffect
hook.
As a result, when there’s a route change, location
changes, and the useEffect
callback is run.
Conclusion
To detect route change with React Router, we can use the useLocation
hook.