Categories
React Answers

How to detect route change with React Router?

Spread the love

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.

One reply on “How to detect route change with React Router?”

This help me a lot, i needed that for my project. You are awesome, Thanks for share this content. =)

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.