Repository navigation
When should router.refresh() be preferred over revalidatePath after a Server Action? #98239
Replies: 2 comments
|
They solve related but different problems. "revalidatePath()" is a server-side cache invalidation API. After a Server Action changes data, use it when cached data associated with a route is now stale and should be invalidated. "router.refresh()" is client-side navigation behavior. It asks Next.js to request a fresh Server Component payload for the current route and merge it into the existing client tree without losing unaffected client state. For a mutation handled in a Server Action, I would generally prefer invalidating the affected data on the server with "revalidatePath()" (or "revalidateTag()" when appropriate). That expresses exactly what became stale. Use "router.refresh()" when the client explicitly needs to refresh the current route's server-rendered data, especially when there is no more targeted cache invalidation available. They can also be used together when necessary: invalidate the stale cache on the server, then refresh the client view if the UI is not already updated as part of the Server Action response. So the distinction is basically:
|
|
One practical rule is to start with the server-side invalidation and only add a client refresh when the UI still needs an explicit reload. In a Server Action, use revalidatePath() when the mutation makes cached data for a known route stale. That keeps the invalidation close to the write and works even when the next request comes from another client. Prefer revalidateTag() when several routes share the same tagged data. Use router.refresh() when the browser is already on the affected route and you need to request a new Server Component payload immediately. It refreshes the current client tree, but it does not replace a server-side invalidation strategy for other users or future requests. For example, a mutation might call revalidatePath('/dashboard') in the action and then rely on the Server Action response to update the current UI. If the current view still contains stale server-rendered data because the mutation happened outside that action, router.refresh() is the client-side follow-up. Using both after every mutation is usually unnecessary. |
Uh oh!
There was an error while loading. Please reload this page.
After a Server Action mutates data, what is the practical difference between calling router.refresh() on the client and using revalidatePath() on the server? In which cases is one preferred over the other to avoid unnecessary rerenders or stale data?
All reactions