skip to Main Content

I’m having a problem on how to refresh my screen when clicking back button from browser. The weird part of this is it’s only replicable when deployed on staging servers. In localhost I didn’t encounter any of this since it refreshes upon clicking the back button.

Here’s my code

 useEffect(() => {
    const handleRouteChange = (url: string) => {
      if (url === router.asPath) {
        router.replace(router.asPath);
      }
    };
    router.events.on("routeChangeStart", handleRouteChange);
    return () => {
      router.events.off("routeChangeStart", handleRouteChange);
    };
  }, [router]);

Expected output

From Screen 1 -> Navigate to screen 2 -> Click browser back button -> Force refresh screen 1

2

Answers


  1. I’ve come across a solution that uses window.location.reload() combined with the beforeunload event to force a page reload. Here’s the code I’m considering:

    import { useEffect } from 'react';
    import { useRouter } from 'next/router';
    
    const MyComponent = () => {
      const router = useRouter();
    
      useEffect(() => {
        const handleRouteChange = (url: string) => {
          if (url === router.asPath) {
            window.location.reload(); // Forces the page to reload
          }
        };
    
        const handleBeforeUnload = () => {
          window.onpopstate = () => {
            window.location.reload();
          };
        };
    
        router.events.on("routeChangeStart", handleRouteChange);
        window.addEventListener("beforeunload", handleBeforeUnload);
    
        return () => {
          router.events.off("routeChangeStart", handleRouteChange);
          window.removeEventListener("beforeunload", handleBeforeUnload);
        };
      }, [router]);
    
      return <div>Your component code</div>;
    };
    

    This solution forces the page to reload when the browser back button is clicked.

    Login or Signup to reply.
  2. With next:14.2.15 and useRouter from next/navigation, I’m able to create a simple example where a random number is displayed in home page.

    When navigating to about page and then select "back" in browser, a new random number will be displayed.

    Without <ClientRouterHandler /> in home page, a cached number will be displayed.

    app/ClientRouterHandler.js (client-side)

    'use client'
    
    import {useEffect} from "react"
    import {useRouter} from "next/navigation"
    
    export default function ClientRouterHandler() {
        const router = useRouter()
    
        useEffect(() => router.refresh(), [router])
    
        return null
    }
    

    app/page.js (server-side)

    import Link from "next/link"
    import ClientRouterHandler from "@/app/ClientRouterHandler"
    
    export const dynamic = "force-dynamic"
    
    async function fetchMockData() {
        const randomNumber = Math.floor(Math.random() * 100)
        return { message: `Hello from server-side rendering! Random Number: ${randomNumber}` }
    }
    
    export default async function Home() {
        const data = await fetchMockData()
    
        return (
            <div>
                <h1>{data.message}</h1>
                <Link href="/about">Go to About Page</Link>
                <ClientRouterHandler />
            </div>
        )
    }
    

    app/about/page.js

    export default function AboutPage() {
        return (
            <div>
                <h1>About Us</h1>
                <p>This is the About Page.</p>
            </div>
        );
    }
    

    Also verified with production build.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search