Detect React Route Change in vanilla JS 🤯

Hi 🙋‍♂️, You are here because you have been looking for a solution to detect a Route Change of your SPA. So how would you detect that the page has been changed? Since there is no navigation as well as no event for the URL change in the spa, we need to come up with our own solution, implement our own Logic.

The first thing we can do is to setInterval, which will check for the prev and current URL changes after a certain interval. A Classic way to do it. This can work with almost all the time and you don't even need an interaction to trigger, it just keeps on checking.

But let just say you do have an Interaction, A Click you can actually check for a client-side route change in a better manner.

Learn more about RequestAnimationFrame() from here 🤓. The above 👆snippet shows that we have a listener on click, so whenever a click event has been triggered, It compares the URL before the click and after the click, if different than the URL has been changed.

👶The reason for writing this article is that I wasted hours on researching and was not able to come up with the proper solution because of not using every specific keyword, and since the medium has a great SEO, it will rank better in google and this how I contribute and help the dev community.

Thank you 🙏

A Resident of the Javascript Rockstar world. The Rockstar himself is actively exploring JOB Opportunities in Germany and Canada.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store