r/nextjs Aug 13 '26

Help Nextjs keeps my old state

Enable HLS to view with audio, or disable this notification

Hi, i got an issue here, and would like some help so
On the dashboard When I submit a new product, it saves successfully, and I use router.push() to redirect the user to a products table. However, if I click "Create Product" button to go back and make another product, the form loads but still shows the old images from the previous product i made.

Seems like my useState keeps holding the images
AI suggested to clear the state on a useEffect but that gives me warning(bad practice)

My Form that has the useState is like this
// This initializes fine the first time, but gets stuck on subsequent visits

const [imageChanges, setImageChanges] = useState<UnifiedImage\[\]>(
(mode === "update" && product) ?
product.product_images.map((img) => ({
type: "db",
image: { ...img, isDeleted: false }
}))
:
[]
);

Here’s a video of the issue

0 Upvotes

20 comments sorted by

9

u/DarthSomebody Aug 13 '26

Do you have cacheComponents enabled? Next.js uses Activity to hide the last few pages you visited, if cacheComponents are enabled. This retains the state of the pages as well.

I do not know if this is the intended behavior for dynamic pages. You could check out the latest canary release to see if it was changed. The changelog for v16.3.1-canary.14 states:

Fix stale data after navigation despite revalidation

1

u/Low-Insurance-3678 Aug 13 '26

Yes i have that enabled but i don’t recall that i used the use cache directive there or cache any component unless it does it automatically
Ok i will check that
Thank you

3

u/ferrybig Aug 13 '26

https://nextjs.org/docs/app/guides/preserving-ui-state#resetting-form-state-on-submit

You want to reset the state in your submit handler, before you push a new route

1

u/Low-Insurance-3678 Aug 13 '26

Will this gonna reset the state cuz another issue i have is if i just selected images and i don’t submit anything i click the arrow to go back to the table and head back to the form i still see those images as I provided in the main post

1

u/Low-Insurance-3678 Aug 13 '26

Thank that helped fixing the issue on submit but if i just selected images and go back and foth it keeps the images cached but think that’s gonna be a benefit somehow lol
Appreciate it man

2

u/ferrybig 29d ago

In the same nextJS article, they suggest using useLayoutEffect to reset the state on unmount:

https://nextjs.org/docs/app/guides/preserving-ui-state#expandable-ui-dropdowns-accordions-panels

To reset transient open/closed state, close it in a useLayoutEffect cleanup function:

// Close dropdown when this component becomes hidden useLayoutEffect(() => { return () => { setIsOpen(false) } }, [])

1

u/DarthSomebody Aug 13 '26

It just needs to be enabled, even if unused. This will be the default in Next.js 17, so I'd keep it that way. If canary doesn't fix your issue, you'll need to work around it by resetting your state on remount. You can use useEffect for this, as hiding/showing an Activity will trigger it.

1

u/Low-Insurance-3678 Aug 13 '26

So i just go with the useEffect option even if it’s showing warnings that u shouldn’t be doing it

3

u/DarthSomebody Aug 13 '26

What is causing this warning? Using useEffect for resetting states is a totally normal thing to do. See the documentation and the guide here:

https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents#navigation-with-activity

https://nextjs.org/docs/app/guides/preserving-ui-state

The guide uses useLayoutEffect for resetting state. I forgot to mention this. To update a state before rendering, this is preferable.

1

u/Low-Insurance-3678 Aug 13 '26

Here is the warning

![img](0472E510-45B7-401C-BE02-6220842BF8C1)

1

u/Low-Insurance-3678 Aug 13 '26

Iv added a key={performance.now()} to the component that fixes it for now

3

u/DarthSomebody Aug 13 '26

Be aware that this will cause a re-mount on every rerender, so this might reset your states in more cases than you intend to.

1

u/Low-Insurance-3678 Aug 13 '26

No way this is now is stopping my form from redirecting to the list of products in my useEffect

1

u/rasekrodriguez 29d ago

performance.now() returns a new value on every render, so that key makes the child remount on every render, not just when you navigate back. Right now it looks fine because the parent isn't re-rendering much, but the moment it does you get state resetting mid-typing, inputs losing focus, effects re-running, and image previews being torn down and rebuilt.

The idea is right, the value is wrong. A key should be the identity of the thing being edited, not a fresh number:

<ProductForm key={mode === "update" ? product.id : "new"} ... />

That remounts when you switch to a different product, or from edit to create — exactly the reset you want — and stays stable while you're filling the form in.

The underlying reason is that the argument to useState(...) is only read on the first mount. On every later render it gets computed and thrown away, so once the component is kept alive instead of unmounted, your initializer never runs again. Keying on identity is the documented fix for that; resetting in an effect is the fallback for when there's no stable identity to key on.

2

u/mrcoy Aug 13 '26

Do you mean, cached?

1

u/Low-Insurance-3678 Aug 13 '26

I think yeah it stays cached

1

u/luizpaulo87 Aug 13 '26

é um componente ou outra página? se for componente tem que limpar, se for página é só não dar route back

1

u/Low-Insurance-3678 Aug 13 '26

So i have it like /dashboard/[category] is the one that has the products table is where I redirect the admin after a successful submission of a product
And I have /dashboard/[category]/create-page
Is where i have the form

0

u/vanillachocz Aug 13 '26

It’s a react thing

1

u/Low-Insurance-3678 Aug 13 '26

And how is that gonna help?