next.js: Page state is not reset for navigating between dynamic routes

Bug report

Describe the bug

The page state is not reset for navigation between dynamic routes that served by the same source component.

for example, give page source /a/[param]/index.js, when navigating from /a/1 to /a/b, states on the page won’t’ be reset.

The causing is that for this kind of navigation, what actually happened is the same React Component been rendered with different props. Thus react takes it as a component is rerendering itself, and causing the new navigated page receive stale states.

To fix it, just add {key: <composed base on URL routing params> } to page initial props.

To Reproduce

I’ve created a live example:

Edit next-bug-dynamic-route-not-rerender

Expected behavior

Page should be fully reloaded and states should be reset.

Screenshots

N/A

System information

  • OS: ALL
  • Browser: ALL
  • Version of Next.js: 9.1.6

Additional context

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 89
  • Comments: 52 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Great find, suggest docs are updated. For future devs, same should be applied in getStaticProps()

export async function getStaticProps({params}) {
    const props = await getData(params);

    // key is needed here
    props.key = data.id; 

    return {
        props: props
    }
}

Fixed with some help from the Discord community - the issue for me was the key sent to my <Component> in _app.jswas wrong, i was previously using:

<Component {...pageProps} key={router.route} />

updating to:

<Component {...pageProps} key={router.asPath} />

fixed it for me

Yes! I’ve seen similar confusing behavior when using useEffect.

  React.useEffect(() => {
    console.log("page initial render");
  }, []);

It only fires once, even when you change the page, but stay on the same route. I’m not sure if it’s wrong, but it’s definitely not intuitive in my opinion. It’s non-intuitive because it works differently when changing the page, but coming from a different route.

I have just come across a solution in my case.

My eg. is involving a link from one page/[id1]/something.js to some other page/[id2]/something.js

The solution for me was:


export default function SomePage() {
    const [something, setSomething] = useState(undefined)
    const router = useRouter()
    const { id } = router.query
    useEffect(() => {
        if (id) setSomething(undefined) // remove the old page data every time the id chages
    }, [id])
 
   const { data, error } = useSWR( id ? '/api/get/' + id : null, fetch)

   useEffect(() => {
      if(data) setSomething(data) // the new Page data
    }, [data])

    return (<div>{something?.whatever}</div>

}

Im still having This issue when using getServerSideProps, any updates?

Fixed with some help from the Discord community - the issue for me was the key sent to my <Component> in _app.jswas wrong, i was previously using:

<Component {...pageProps} key={router.route} />

updating to:

<Component {...pageProps} key={router.asPath} />

fixed it for me

Great… and now the question is… why this isn’t a default setting?

PS: @samuelgoddard great site design 😉

Fixed with some help from the Discord community - the issue for me was the key sent to my <Component> in _app.jswas wrong, i was previously using:

<Component {...pageProps} key={router.route} />

updating to:

<Component {...pageProps} key={router.asPath} />

fixed it for me

This works thanks a ton ❤️

Custom _app.tsx with <Component {...pageProps} key={router.asPath} /> definitely solved my issue. Wish I had landed on this issue before killing so many hours on this.

As @valse point out, why isn’t this the default? @Timer, could this be considered?

To fix it, just add {key: <composed base on URL routing params> } to page initial props.

You literally saved me hours of pain. I was trying to use effect cleanups to get around my issue but this is all I needed. Thank you.

OMG this keyed solution is magic! But shouldn’t this be the default behavior for dynamic routes? In my blog post page I had some “refresh” issues navigation client side and I didn’t understood why… until now 😛

Confirming that

Page.getInitialProps = (c) => {
  return {
    id: String(c.query.id),
    key: String(c.query.id),
  };
};

Produced the expected mount/unmount effects that @Janpot mentioned.

I’ve been having this same issue and been able to mostly solve it (in many places) using react key properties on my markup that contain the dynamic route value… For example…

For a route that uses a [lang] property to change language… e.g. /[lang]/page1

<Page key={'page_' + props.lang}>...</Page>

Setting the unique key based on the property seems to let react know to re-render the items… it seems even if the data of the page is different, when there is the same fundamental component, react doesn’t know to properly update the components on the page. Figured I’d share what seems to be working for me in a lot of cases.

Fixed with some help from the Discord community - the issue for me was the key sent to my <Component> in _app.jswas wrong, i was previously using:

<Component {...pageProps} key={router.route} />

updating to:

<Component {...pageProps} key={router.asPath} />

fixed it for me

This worked for me as well. Thank you. To add, just for completeness, the router is the value defined using useRouter

import { useRouter } from "next/router";
const router = useRouter();    /* Inside the component */

The working solution is that from @samuelgoddard adding the router.asPath key to the _app page Component: <Component {...pageProps} key={router.asPath} />

Also experiencing issues with getStaticProps and browser back, even after adding a unique key to the props return.

This feels so wrong but it’s working and I can’t find a better solution.

Using next version 10.0.4.

export default function Page({
  data,
}) {
  const router = useRouter();
  const uid = useRef(router.query.uid);

  /**
   * If for some reason this component has stale props from navigating back by
   * browser history, reload the entire page.
   *
   * @see {@link https://github.com/vercel/next.js/issues/9992}
   */
  useEffect(() => {
    if (router.query.uid != uid.current) {
      router.reload();
    }
  }, [router.query.uid]);

  return <div>...</div>;
}

export const getStaticProps = async ({ params, previewData = {} }) => {
  const data = await queryByUid('product', params.uid, {
    ...previewData,
  });

  return {
    props: {
      data,
      key: params.uid,
    },
    revalidate: 60,
  };
};

export const getStaticPaths = async () => {
  const { results } = await queryByType('product');

  const paths = results.map((result) => ({
    params: {
      uid: result.uid,
    },
  }));

  return {
    paths,
    fallback: false,
  };
};

The problem with using the key prop in getStaticProps is that, while going from one page with dynamic props to another one with different props will work, going back (using window.history.back()) will only show the last page with dynamic props that was reached.

/a/1 ---> /a/2 ---> /a/3 ---> /a/4 ---> /a/5 This will work ok with key in props. /a/5 <--- /a/5 <--- /a/5 <--- /a/5 <--- /a/5 This is how the pages will render when using history.back() while having key in props.

Any solution?

@BananaWanted I just got this exact issue and thanks to @Janpot he pointed me to this post and tried your solution and it worked for me.

I’m not sure if this is a “next router” issue or a react issue, but even with your workaround/solution sometimes the browser back button doesn’t work as expected, so I think this should be fixed.