6

In < Next 13 (or with appDir disabled), you could do:

const MyComponent = () => {

  const router = useRouter();

  const toggleStatic = () => {  
    if (router.query.static) {
      router.push(router.pathname, router.pathname, { shallow: true });
    } else {
      router.push(router.pathname, router.pathname + "?static", { shallow: true });
    }
  }

  return <>
    // ...
  </>

});

This would perform a shallow router update that would change the location, but not push it to history or trigger a page load.

Now, with appDir enabled, you need to import functions from next/navigation instead. But the docs don't say anything about shallow router pushing using the new router?

All I can do is this:

const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const toggleStatic = () => {
  if (searchParams.get("static")) {
    router.push(pathname);
  } else {
    router.push(pathname + "?static");
  }
};

But that does a full page reload. Is there a way to replicate the shallow router functionality using Next 13's appDir?

brandonscript
  • 68,675
  • 32
  • 163
  • 220

1 Answers1

1

Try the replace method instead of push:

const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();

const toggleStatic = () => {
  if (searchParams.get("static")) {
    router.replace(pathname);
  } else {
    router.replace(pathname + "?static");
  }
};

useRouter in nextjs docs.

dom1
  • 425
  • 1
  • 2
  • 19