Run Code Before Route Change In NextJS

While building a website sometimes you might need to run some specific code before the route changes and after the route changes in your NextJS app. The best use case is setting loader variables. A Page loader is simply animation or gif that you show to user until your page is ready with the data to be displayed. In order to run the code before Route changes and after route changes you can use some techniques from React Router but here we are going to use a much simpler and powerful NextJS feature to implement this. is something that allows you to listen to different next/router events in your JSX component. The two events that we will use in this example are routeChangeStart & routeChangeComplete.

  • routeChangeStart: accepts a callback which runs when the route change is initiated.
  • routeChangeComplete: accepts a callback that runs once the route has changed.
import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function MyApp({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {'routeChangeStart', (url, { shallow }) => {
      console.log(`App is changing to ${url}`)
    })'routeChangeComplete', (url, { shallow }) => {
      console.log(`App is Changed to ${url}`)
    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
  }, [])

  return <Component {...pageProps} />

This is a simple example for next/router events you can read about more events in the documentation. If you have any questions or face any issues comment below or reach out to me via social media @manorinfinity.

ManOrInfinity Written by:

Coding, Fitness, Writing are three of my passions. I am a bit complicated in my mind but fairly simpler outside. Sharing my knowledge and learning from others are two of my best qualities. One last thing. I don't like to reveal too much about myself!

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.