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:
- 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....
Jump to solution
6 Replies
shane
shane10mo ago
I tried using a server action to pull data for a dashboard
server actions are meant for mutations (internally they use the POST method). do your data fetching in your (server) components.
Cookies
CookiesOP10mo ago
is app/api/getData/route.ts considered a server component?
shane
shane10mo ago
that's a route handler, which is not a server component (but does still run on the server)
Cookies
CookiesOP10mo ago
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
shane
shane10mo ago
- 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.
Cookies
CookiesOP10mo ago
Thank you
Want results from more Discord servers?
Add your server