Mutations
Advantages of using Server Actions for data mutations:
Server Actions allow you to run asynchronous code directly on the server, eliminating the need for API endpoints to mutate data.
Invoking a Server Action within a Server Component allows forms to work even if JavaScript has not yet loaded on the client.
Server Actions are deeply integrated with Next.js caching.
When a form is submitted through a Server Action, you can also revalidate the associated cache using APIs like revalidatePath and revalidateTag.
📋 Examples
The examples below help us understand situations where not revalidating the cache on-demand would lead to undesired effects. Imagine that a user wants to remain on the same page after updating a form. We would expect that the new data would immediately be displayed after submitting the form. That is what happens in example 1, but not in example 2.
Please update the value and submit.
Behind the scenes, a server action that updates the data and revalidates the path will be invoked.
Cached data will be purged and the UI is updated with fresh data.
💡 Notice that the value you submitted is immediately displayed in the card below the form, as expected.
Update Form 1
Please update the value and submit.
Behind the scenes, a server action that only updates the data will be invoked.
Since no revalidation was triggered, the old cached data will keep showing in the UI.
💡 Notice that if we refresh the page, or even press the submit button on the form 1 (which revalidates the whole path), we would then see the updated data.
Update Form 2
This is just a simple example and what happens with the cache in Next.js is usually complex. The important thing to take note of is that understanding the caching mechanism of Next.js and how to manipulate it is extremely important to prevent unexpected behavior and bad user experience.