I recently encountered an issue where the state of a component was not getting refreshed when navigating with the Next.js router. After some investigation, I discovered the problem and found a solution.
In my case, I had a component that used the useState() hook to manage some variables. However, even though I expected the state to update when navigating to a different page, it remained unchanged.
Upon further examination, I realized that the issue was related to my custom _app.js
file. This file was initially copied from a tutorial and primarily used to add global styling to my app. It had the following code:
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
}
To fix the problem, I made a simple modification by importing the useRouter hook from the “next/router” module and using the asPath property as the key for the Component:
import { useRouter } from 'next/router'
export default function App({ Component, pageProps }) {
const router = useRouter()
return <Component {...pageProps} key={router.asPath} />
}
By adding the path as a key, the state of my component started to refresh as expected when navigating with the Next.js router.
In conclusion, if you encounter a situation where the state of a Next.js component is not refreshing on navigation, double-check your custom _app.js
file. Make sure that you are passing a unique key to the component using the useRouter hook and the asPath property. This simple adjustment can resolve the issue and ensure that your component’s state is properly refreshed when navigating with the router.