Reputation: 467
I'm trying to change the background on an element on click on a specific route using the useState
hook. The background of element is changed but it has been changed on the other pages as well. Is there any way that the background of the element can be set back to default on the route change and use the hook on a specific route only ?
Upvotes: 0
Views: 5596
Reputation: 2939
For those having the same issue, you can simplily assign new value to key property on the component you are rendering, Next.js will reset the state of that component when the key property changes.
For example:
import { useRouter } from 'next/router';
import YourComponent from 'components/your-compoennt';
export default function YourPage() {
const router = useRouter();
return (
<YourComponent key={router.asPath} />
)
}
Hope it helps
Upvotes: 4
Reputation: 3614
You can use next/router
to track when the route has changed. There are probably several ways to achieve what you want. But maybe the cleanest is to simply listen to the route change events:
https://nextjs.org/docs/api-reference/next/router#routerevents
Or you could track the value of pathname
. Kind of depends on your needs.
Upvotes: 1