#Dynamic route with Link component not resetting component state
1 messages · Page 1 of 1 (latest)
In Next.js, when navigating to the same page, the page's state will not be reset by default as React does not unmount unless the parent component has changed. This is because Next.js uses "soft navigation" which only re-renders the route segments that have changed, preserving the client React state during navigation.
If you want to reset the state when navigating between pages, you have a couple of options:
- Manually reset the state using
useEffect: You can use theuseEffecthook to reset the state whenever the route changes. Here's an example:
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
export default function Header() {
const router = useRouter()
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
setIsOpen(false)
}, [router.asPath])
// rest of your component
}
In this example, useEffect will run every time router.asPath changes, which happens every time you navigate to a new page. When it runs, it sets isOpen to false, effectively resetting the state.
- Use a React
keyto force the component to remount: You can use a Reactkeyto tell React to remount the component whenever the key changes. In this case, you can use the route as the key. Here's an example:
import { useRouter } from 'next/router'
export default function MyApp({ Component, pageProps }) {
const router = useRouter()
return <Component key={router.asPath} {...pageProps} />
}
In this example, the Component will remount every time router.asPath changes, which happens every time you navigate to a new page. When it remounts, it will reset its state.
Sources:
- Resetting state after navigation (https://nextjs.org/docs/pages/api-reference/functions/use-router#resetting-state-after-navigation)
- Soft Navigation (https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#5-soft-navigation)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@potent canopy kapa.ai is still learning and improving, please let us know how it did by reacting below