Challenges

Live Reloading for a Production Next.js app

Add Live Reloading Support

Now we are going to add the live reload functionality. For that, we need an additional NPM package. Install that with:

yarn add swr

Now create a file called lib/use-live-reload.js and add this content.

import useSWR from 'swr'
import {useRouter} from 'next/router'
import { useEffect, useState } from 'react'

async function textFetcher(path) {
    const res = await fetch(path)
    return res.text()
}

export default function useLiveReload() {
    const router = useRouter()
    const [prevData, setPrevData] = useState(null)
    const {data} = useSWR(router.asPath, textFetcher, {
        refreshInterval: 1000,
    })

    useEffect(() => {
        if (!data) {
            return
        }

        if (prevData && prevData !== data) {
            location.reload()
            return
        }

        setPrevData(data)
    })

    return {}
}

Then import this file on the pages/index.js with:

import useLiveReload from '../lib/use-live-reload'

Finally, invoke the useLiveReload React hook inside the Index page. The final version of pages/index.js will look like this:

Now, let's do the same experiment again:

  • Kill the already running app
  • Run your app with yarn build && yarn start
  • Visit http://localhost:3005 using a new browser tab
  • Then open the data/content.md file
  • Change the content
  • Check the content of http://localhost:3005 for 5 seconds
  • Reload the page twice
Q: How do you describe the result?
authenticating...

It's time for another question.

Q: Why did we use SWR React hook and what it does?
authenticating...