Next.js Discord

Discord Forum

how do you force unmount of an entire page/component when going back/forward browser history?

Unanswered
Havana posted this in #help-forum
Open in Discord
Avatar
HavanaOP
i'm having way too many bugs when i go back in history and go forward. I want to trigger a full refresh of the page, how do i do this? When i go back the component is still running in the background, i can hear stuff from the webgl side and audio. Then when i go forward in history it's just a black screen and a mess.

18 Replies

Avatar
Well I think there is a workaround to do that
but I feel like it will be not that good for performance
import { usePathname } from 'next/navigation'

export default function RootLayout({ children }) {
  const pathname = usePathname()

  return (
    <html lang="en">
      <body>
        <div key={pathname}>
          {children}
        </div>
      </body>
    </html>
  )
}
thinking this should do what you want but I don't recommend this
and browser b/f cache is out of control I guess
Avatar
Dwarf Hotot
To full refresh the page you can use router.refresh() method to refresh the page
Avatar
lol how do you get that event? b/f
Avatar
Dwarf Hotot
Import useRouter from next/navigation

Const router = useRouter ();

Then you can use router.refresh() method any where you when you want to refresh the page
Avatar
anywhere? what if I want to use router.refresh() when user click on b/f button in the browser
Avatar
Dwarf Hotot
Yes you canjust call this event in the on click function
Avatar
oh
Avatar
Dwarf Hotot
Yes
Avatar
b/f button in the browser is not part of html dom
how can you get onclick event???
Avatar
Dwarf Hotot
When you want to refresh the page
Avatar
check what OP wants
Avatar
Dwarf Hotot
You can call in the use effect event
Avatar
HavanaOP
I tried a similar key based approach by hooking into the popstate evt but it didn't work, so i just added a state shouldRefresh. On popstate it becomes true, and as soon as it goes on the other page i call window.location.reload. For right now it's working. I'll try your other key method tomorrow, thanks. I was hoping there was some more defined and tested way to do this