Understanding When To Use Server Actions
As a newer next.js dev it is a little bit overwhelming all the different ways to fetch data for your app. When should I be using server actions over calling an API route. I keep seeing random post and videos essentially saying you can move away from TRPC or API routes with server actions. I tried using a server action to pull data for a dashboard I was creating but got an error saying server actions cannot be utilized on initial render.
Can someone help me understand the best use cases and advantages of one over the others.
Solution:Jump to solution
- server components: React components that are rendered only on the server (not included in client bundle). they can be async and fetch data, etc.
- server actions: functions executed on the server that can be called by server and client components....
6 Replies
I tried using a server action to pull data for a dashboardserver actions are meant for mutations (internally they use the
POST
method).
do your data fetching in your (server) components.is app/api/getData/route.ts considered a server component?
ok, I do understand a server component is something that runs on the server vs the client. Just a little confused on server actions and server components
but the examples I have seen for server actions have all been mutations so that I think that clears things up a bit.
Solution
- server components: React components that are rendered only on the server (not included in client bundle). they can be async and fetch data, etc.
- server actions: functions executed on the server that can be called by server and client components.
Thank you