Run Code Before Route Change In NextJS

Last updated on February 3, 2023

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 need help implementing this is your nextjs project ping me on twitter @manorinfinity.

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

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