勇哥

勇哥开发之路

I build things on web.

Use Next.js's router.push to achieve partial page refresh.

Scene#

"New Conversation" is a common feature of AI dialogue applications.

When Yong started developing the AI dialogue application, it was based on Next.js + shadcn/ui. When implementing the "New Conversation" feature, it naturally used Next.js's router.push() to route to the new conversation.

Problem#

However, during actual testing, it was found that the page sometimes does not re-render, even though it has already routed to the new conversation address, and the page content remains the old page.

Solution#

Analysis revealed that router.push() sometimes does not trigger a complete page re-render, especially when the URL parameters change but the path remains the same. This is due to the client-side navigation optimization mechanism adopted by Next.js by default.

So the following modifications were made:

...
export function NewChat() {
  ...
  return (
    <Suspense>
      <Button onClick={async () => {
        const newChat = createQueryString('newchat', 'true')
        await router.push(newChat)
        router.refresh()
      }}>
        <Plus /> New Conversation
      </Button>
    </Suspense>
  )
}

Explanation#

  • Added async/await to ensure navigation completion
  • Used router.refresh() to ensure refresh is executed after push is completed, ensuring the page is correctly re-rendered after navigation

Additionally, some state management can be added to ensure the component is indeed re-rendered. Alternatively, window.location.reload() can be added as a fallback after navigation, but this will cause a complete page refresh, which is not a good experience.

Aside#

Later, I saw the open-source AI Chatbot from Vercel, which is also based on Next.js + shadcn/ui, which is quite coincidental.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.