Development

Detect React Route Change in Vanilla JavaScript


Wondering how would you listen to page change for the spa in a Virutal DOM which is routing through client-side routing via vanilla javascript.

Detect React Route Change in Vanilla JavaScript

Hi! You are here because you have been looking for a solution to detect a route change in 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 and implement our own logic.

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

But let’s just say you do have an interaction — **a click — **you can actually check for a client-side route change in a better manner.

let url = location.href;
document.body.addEventListener('click', ()=>{
    requestAnimationFrame(()=>{
      if(url!==location.href){
        console.log('url changed');
        url = location.href
      }
    });
}, true);

Learn more about *RequestAnimationFrame()* from here. The above snippet shows that we have a listener on click, so whenever a click event is triggered, it compares the URL before the click and after the click. If they are different, then 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 Medium has a great SEO, it will rank better on Google and this how I will contribute to and help the dev community.

Thank you!

Raja Osama

I Describe Myself as a Polyglot ~ Tech Agnostic ~ Rockstar Software Engineer. I Specialise in Javascript-based tech stack to create fascinating applications.

I am also open for freelance work, and in-case you want to hire me, you can contact me at rajaosama.me@gmail.com or contact@rajaosama.me