-1

I'm building an eCommerce website using Next.js. Everything loads and navigates correctly when browsing categories or product pages using links. However, I'm running into an issue when using the browser's back button (e.g., Chrome).

When I navigate forward to a product or category page, it renders as expected. But when I hit the back button, while the URL in the address bar updates correctly to the previous route, the page content does not update — it stays stuck on the most recent view.

I'm using dynamic routes like /product_category/[slug] and client-side navigation with next/link or router.push. My components rely on useRouter and router.query to fetch data based on the slug.

Is this a common issue in Next.js routing? How can I make sure the page content updates properly when navigating backward?

1 Answer 1

0

When using router.query.slug in dynamic routes (/product_category/[slug]), the value may initially be undefined when navigating back. This can cause your data-fetching logic to fail or not re-run, leading to stale or missing content.

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
    
export default function CategoryPage() {
    const router = useRouter();
    const { slug, isReady } = router;
    const [categoryData, setCategoryData] = useState(null);
    
    useEffect(() => {
        if (!isReady) return;
        const fetchData = async () => {
        const res = await fetch(`/api/category/${slug}`);
        const data = await res.json();
        setCategoryData(data);
    };
    
    fetchData();
}, [slug, isReady]);
    
if (!categoryData) return <div>Loading...</div>;
    return <div>{/* Render category content */}</div>;
}

Add key to force remount.

Sometimes forcing a component remount can also help if state isn’t resetting correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.