useRouterQueryParam() instead of useRouter() for performance #45969
Unanswered
alex-statsig
asked this question in
Help
Replies: 1 comment 3 replies
-
For completeness sake, in appDir, there's dedicated hooks for this:
For example the new use-router, doesn't include data, but only actions, such as push, replace, etc. It'd be nice if they could bring in that appDir feature into the pages directory, but that'd be a breaking change I guess. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Problem
I've realized that most usages of useRouter() throughout my app are either
router.push()
orrouter.query.xyz
. Components using this hook will rerender on any "navigation" (including pseudo-navigation where filters are encoded in the URL for example) due to the context change of useRouter() (useRouter is basicallyuseContext(RouterContext)
under the hood).Request
I'm wondering if anyone has made a handy hook for accessing a router query param without rerendering on all route changes. It seems like it would be possible via subscribing to router events instead of using useRouter, but also feels like it should be provided by nextjs given how low-level any widespread it is.
One concern I have with doing it manually is potentially falling out of sync with the correct router params during transitions (ex. I think suspense is used during a page transition, and needs to rerender with the new router params before the global route updates).
Note: router.push() can be solved by using the static
Router.push()
insteadExample
Example current logic using
useRouter()
for pathname, which rerenders on any query param change:Potential optimized version which only rerenders if pathname actually changes:
However, it is broken as it doesn't get the "pending" router state, only the global state (which doesn't update until the new route is done being rendered)
Beta Was this translation helpful? Give feedback.
All reactions