-
-
Notifications
You must be signed in to change notification settings - Fork 199
Description
Context
What's your version of nuqs
?
2.5.1
What framework are you using?
- ✅ Next.js (app router)
- ❌ Next.js (pages router)
- ❌ React SPA (no router)
- ❌ Remix
- ❌ React Router
- ❌ Other (please specify)
Which version of your framework are you using?
15.5.2
Description
After setting a new value the state returned by useQueryState
temporarily resets to its previous value when the component is rerendered multiple times due to some other state changes (e.g. loading new data based on new state).
After calling the state setter function of useQueryState
with a new value the component rerenders four times with the newly set value. That's fine. But if this new value causes other state changes (e.g. data fetching) there are two rerenders where useQueryState
suddenly returns the previous value. Then on further rerenders the newly set value is returned again.
Taking the reproduction demo a console.log
directly in the rendering process outputs the following (annotated with comments for better explanation):
// Click on button which sets the state "desc"
Rendering with sort order: desc
Rendering with sort order: desc
Rendering with sort order: desc
Rendering with sort order: desc
// Now the unexpected two renders with the previous value !!!
Rendering with sort order: asc
Rendering with sort order: asc
// Now the value switches back to new value again
Rendering with sort order: desc
Rendering with sort order: desc
Rendering with sort order: desc
Rendering with sort order: desc
...
Reproduction
https://github.com/georgwittberger/nuqs-errors-repro
https://stackblitz.com/github/georgwittberger/nuqs-errors-repro
- Install dependencies, then start dev server:
npm run dev
- Open demo page: http://localhost:3000/reset
- Open browser dev tools and view Console tab.
- Click button "Sort desc".
- Notice there are rerenders with the previous value "asc" after new value "desc" has already been set.
This also fails unit tests that assert the new value.
Run npm run test
and see failing test in src/app/reset/page.test.tsx
. This test is expected to succeed.
After data for new state "desc" has been rendered the test simply checks if the rendered state value is still "desc" but fails because it hits the render output with the previous value "asc".