How do I listen for window load upon each route change in react router?

Viewed 2528

I am building a project with react-router that has multiple routes. The code looks like this:

<Router>
  <div className='main'>
    <Header />
    <div className='main-content'>
      <Switch>    
        <Route exact path="/about" render={({history: {location}}) => <About/>}/>
        <Route exact path="/contact" render={({history: {location}}) => <Contact/>}/>
        <Route exact path="/blog" render={({history: {location}}) => <Blog/>}/>
      </Switch>
    </div>
    <Footer /> 
  </div>
</Router>

In the component for each route I am adding a lifecycle method ComponentDidMount(), setting an event listener for 'load' and then running a callback.

componentDidMount() {
  window.addEventListener('load', () => this.handleLoad());
}

handleLoad() {
  console.log('this page loaded');
}

This works as expected on the first route that loads and the console will log 'this page loaded'. However, when any subsequent route is requested the event listener no longer listens for load of the next component (maybe because the event listener is still in place?)

How can I listen for page load on multiple routes?

1 Answers

Based on my knowladge whole react app loads on user pc at once, and then it just changes the look based on routes, and won't take any time to load. But you can listen api fetchs if you want.

Related