Next.js Server Actions (revalidatePath, useFormStatus & useOptimistic)

  Рет қаралды 122,084

ByteGrad

ByteGrad

Күн бұрын

Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
👉 Add auth to your app FAST: bit.ly/3QOe1Bh
👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
👉 Professional JavaScript Course: bytegrad.com/courses/professi...
👉 Professional CSS Course: bytegrad.com/courses/professi...
👉 Discord: all my courses have a private Discord where I actively participate
🔔 Email newsletter (BIG update soon): email.bytegrad.com
⏱️ Timestamps:
0:00 Fetching data in server components
0:58 Traditional data mutations
2:54 Server actions for mutations
6:37 Revalidating data
8:08 Under the hood
9:28 2 Other Benefits
10:31 Server Action in client component
13:20 Reset form
15:44 Downside of client components
16:06 useFormStatus (pending state)
18:20 Error handling
19:55 useOptimistic (optimistic UI)
26:29 formAction
27:10 Server Actions outside form
#webdevelopment #programming #coding

Пікірлер: 201
@ByteGrad
@ByteGrad 5 ай бұрын
Hi, I just released my new React & Next.js course: bytegrad.com/courses/professional-react-nextjs
@angelbythewings
@angelbythewings 3 ай бұрын
Hey it would be good, if you can add a breadcrumb extension to your vscode, so users know the path of the page you are on
@ricardourbieta
@ricardourbieta 7 ай бұрын
I was blown away by how cristal clear is the way you explain and showed this topic, with the example use case, I've been particularly struggling with this for a few weeks, thanks a LOT
@ByteGrad
@ByteGrad 7 ай бұрын
Glad it was helpful!
@appstuff6565
@appstuff6565 8 ай бұрын
Hi ByteGrad, first time discovering you and I love the explanation you did. So simple along with theory and simple example.
@filipesommer8253
@filipesommer8253 9 ай бұрын
This video is fantastic. The way you also care about possible errors in real-world use cases and not just the "happy path" is much needed in the KZfaq dev space
@koolam5158
@koolam5158 2 ай бұрын
exactly
@ZainabSalah-xm1xy
@ZainabSalah-xm1xy 7 ай бұрын
this is amazing !!!!!!!!!!!! i searched so much to know these and u just have them all in the best way ever
@sahaneakanayaka3394
@sahaneakanayaka3394 7 ай бұрын
Your tutorials are awesome. Everything is crystal clear ... 😍😍
@dallinromney
@dallinromney 4 ай бұрын
Incredible video thank you!!!! Game changer. Note @17:59 the bit of extra lag between the form pending and the new item pending in the list is simply the extra data fetch from the revalidation, since the form is only pending the creation, not the revalidation (correct me if I'm wrong experts). But as you explained seems like useOptimistic is the way to go to fix this!
@appstuff6565
@appstuff6565 8 ай бұрын
Half way to the video and i loved the fact first you tried to make us understand in a single file and then slowly organized it into a proper folder structure patterns. Loving it so far.
@user-rv1bx8hx4v
@user-rv1bx8hx4v Ай бұрын
@robertodelgado598
@robertodelgado598 9 ай бұрын
This is easily the most helpful video I’ve seen about forms in next. I was about to lose my mind with forms last week, maintaining states. THANK YOU!!!
@appstuff6565
@appstuff6565 8 ай бұрын
same here.
@rawnato
@rawnato 6 ай бұрын
In some cases, I still prefer using an API, especially for cases where your web system also shares data with phone apps! but for web systems that don't need to share data, I think it's a good solution!
@alexedev
@alexedev Ай бұрын
Thank you for clear and quick delivery, you are very nice teacher
@dickroach
@dickroach 6 ай бұрын
You explain really smooth, fast, useful and accurate I really enjoy and learn many things
@zahidulhaquejony
@zahidulhaquejony 8 ай бұрын
Your amazing. I learned few new things. I always watch your video when i get free time. Keep going. Take love from Bangladesh ❤️🇧🇩
@tigranharutyunyan7674
@tigranharutyunyan7674 3 ай бұрын
Great info presented here. Thank you. Nuxt misses this feature.
@roshanpaudel6352
@roshanpaudel6352 8 ай бұрын
Really great content !! Loved It. i was amazed by how much can We do using server actions.
@sergeiiandreiev7391
@sergeiiandreiev7391 6 ай бұрын
Thanks for video! It`s amazing because you answer on questions *why * and "how* both . And also it`s not a starting level on my opinion. So waiting to your full course )
@edhahaz
@edhahaz Ай бұрын
I can totally see the vision, but oh man it's a lot of concepts building on top of each other.
@DevranDenizzz
@DevranDenizzz 5 ай бұрын
Simple and direct tutorial.thanks
@darkcss1054
@darkcss1054 2 ай бұрын
Well, your tutorial is actually better than the one the Next.js team itself offers. It's a relief that as a React/Next newcomer, I don't have to jump through the hoops the guys on Next.js 13 tutorials I'm watching had to.
@darocha
@darocha 5 ай бұрын
Love your content! It's my favourite channel. ❤
@based__ai
@based__ai 8 ай бұрын
Appreciate the content -- your videos are quite good. If you're brainstorming future videos, it might be valuable to dig a layer deeper on some of the topics you covered to get at the 'why', ie, the underlying architecture driving the behaviors demo'ed. This would likely require working through the documented caching mechanisms along with, perhaps, looking at network requests in greater detail, etc. In all events, thanks again.
@reactwind
@reactwind 6 ай бұрын
THANK YOU SO MUCH WITH THE CLENT COMPOENT!
@rohitdalal954
@rohitdalal954 5 ай бұрын
this video is really great. thank you so much 😄🙌
@anangyoga1381
@anangyoga1381 3 ай бұрын
thank you. you saved my time learning this
@tacituskilgore2258
@tacituskilgore2258 9 ай бұрын
Very underrated channel, dude Love your content!!
@backstromforsberg
@backstromforsberg 8 күн бұрын
This is so much better than the docs lmao
@MCTVARG
@MCTVARG 6 ай бұрын
Amazing video, a real summary, better than reading the docs. After watching your video and trying it out, being a nextjs user for long I just fail to see the benefit of going this route. I guess it does have benefits if your using next as your standalone application, but client components work just fine for forms, and its the way we've been doing things for long. All of these experimental tags seem just wrong. Having a todo item appear, and then dissapear feels like bad UX. I really wanted to like server actions, but so far I think I will stick with server components just for rendering initial data.
@mariusradu3849
@mariusradu3849 4 ай бұрын
Holy shit I wished I had this man as one of my college prof. The quality is top. The only dubious thing I need to mention is that he talks like he tryna charm you or something 😅 . Liked ✅ subscribed ✅
@kevinmonaar7089
@kevinmonaar7089 6 ай бұрын
This is very helpful! Thank you.
@Sokoladomeistrai-kq1to
@Sokoladomeistrai-kq1to Ай бұрын
Six words to support the channel
@hyper_channel
@hyper_channel 5 ай бұрын
Something to consider with optimistic UI patterns is that for certain actions the users "distrust" an overly fast update, there have been studies about this where the user expect certain operation to happen and have some delay and when it seems to complete instantly is deemed suspicious.
@deadchannel8431
@deadchannel8431 5 ай бұрын
This made me feel better about my slow websites lol
@user-ri1vc4qv8j
@user-ri1vc4qv8j 4 ай бұрын
True. I was thinking that when he used it.
@inderjotsingh5868
@inderjotsingh5868 3 ай бұрын
epitome of clear explanation
@9ernation4-life40
@9ernation4-life40 7 ай бұрын
Thanks! Awesome Tutorial very helpful for me
@ByteGrad
@ByteGrad 7 ай бұрын
Thanks, appreciate it!
@DagmarJS
@DagmarJS 2 ай бұрын
Thank you for the video!
@RicardasSv
@RicardasSv Ай бұрын
It is clear and well-explained, and not a creator issue. But it will take one or two seconds. Okay, I'm done here. Thank you.
@lee45283
@lee45283 6 ай бұрын
Super helpful! Thanks.
@emmanuelalfred8557
@emmanuelalfred8557 8 ай бұрын
Your videos are truly helpful, I hope this comment encourages you to not stop educating us(me) anytime soon
@thedigitalceo
@thedigitalceo 26 күн бұрын
Great video!
@JoaoLucas-tw2pt
@JoaoLucas-tw2pt 6 ай бұрын
Fantastic, very well mate
@amitjohn8736
@amitjohn8736 9 ай бұрын
this is amazing i loved it. hope n your upcoming next js full stack course you explains in same way
@ByteGrad
@ByteGrad 9 ай бұрын
That's the plan!
@nick-ui
@nick-ui 9 ай бұрын
Now I understand server actions, ty
@faicalbahsis5659
@faicalbahsis5659 8 ай бұрын
its a fantastic video thank you
@pikelele
@pikelele 2 ай бұрын
great tut
@LeighBriody
@LeighBriody 8 ай бұрын
Great video thank you
@dutchprime1488
@dutchprime1488 6 ай бұрын
Im 10 minutes in and already learned so much
@SXsoft99
@SXsoft99 9 ай бұрын
basically action controller that does only one thing, i just love the reactJS guys trying to reinvent the wheal, or at least rename it
@parkerrex
@parkerrex 9 ай бұрын
This is money. SO happy I found this.
@sealuke2724
@sealuke2724 8 ай бұрын
super useful!!!
@Thopsp
@Thopsp 9 ай бұрын
Happy to follow you
@alexg7282
@alexg7282 7 ай бұрын
Thanks a lot !
@xhwogusxh
@xhwogusxh 7 ай бұрын
You are GENIUS!!! SUPER THANKS!!! God bless you!!! You're gonna be super rich!!! SUPER THANKS!!!
@y0ssef
@y0ssef 6 ай бұрын
21:50 here you can use the prisma auto generated Todo type (if your data types are all primitive [for example if the id is Int and not BigInt] which is the case mostly)
@naman_dw
@naman_dw 8 ай бұрын
I will stick with client component and shad cn forms, I think. Much cleaner and natural api. 18:00 : that lag is probably because pending state is only true while form is submitting, but then it takes some time to revalidate the cache, and during that time the pending state is false
@georgegeorgio70
@georgegeorgio70 7 ай бұрын
Super kontent masz! Bardzo klarownie tłumaczysz i super się to ogląda. Propsy ziomuś! :) Ps. Nie udzielasz może prywatnych korepetycji?
@ByteGrad
@ByteGrad 7 ай бұрын
Thanks! Looking into private tutoring, do you have any examples of other people doing this?
@georgegeorgio70
@georgegeorgio70 7 ай бұрын
@@ByteGrad if that would be possible count me in !
@codingtranquility
@codingtranquility 3 ай бұрын
Here I was hearing "server actions" and thinking "oh great, more stuff to learn to be able to do stuff I've already been doing for years". Meanwhile the autocomplete for form had me using it without even realizing what it was. Good times.
@marcialabrahantes3369
@marcialabrahantes3369 3 ай бұрын
great content! the constant screen resizing is a bit annoying, however :) i'm watching in 2x so that's likely is part of it (i.e. higher frequency)
@Randomuser7890
@Randomuser7890 Ай бұрын
Great...!
@guivasconcelos21
@guivasconcelos21 8 ай бұрын
I wonder how it'd look like if you had another action to mutate the list in the same component. For instance, a delete or toggle todo. Would it be 2 different useOptimistic calls?
@Eventyret
@Eventyret 9 ай бұрын
Great video good explanation 🎉 What's the react extension you use or snippet for creating components like that? Also what's the Mac app you use to show the app icon when moving apps. Thank you again ❤
@tek9ine130
@tek9ine130 9 ай бұрын
The extension is React Snippets. The icons that show up when resizing the windows is a Windows 11 feature, he's not on Mac I believe.
@thomasschmidt73
@thomasschmidt73 6 ай бұрын
Regarding the optimistic stuff: will it replace the Math.random() id with the actual id after the server action has finished?
@jcbraz
@jcbraz 9 ай бұрын
In your point a view, what would be the best approach to fetch data from a Client component that does not require a form? Would the /api folder still be required? Is there a better option? Thanks for the great video.
@Anthymn
@Anthymn 8 ай бұрын
I would make a custom hook in the client component that has the data I need to fetch, then I can just call that hook anywhere I need that information. Not sure if this is helpful for your case.
@dimakavetskyy2082
@dimakavetskyy2082 7 ай бұрын
super cool
@coleblender
@coleblender 3 ай бұрын
Is there a way to add a revalidation tag to the todos fetch at the beginning of the video or can that only be done if you use fetch?
@ktrifon
@ktrifon 4 күн бұрын
What if this form was a search form and below you wanted to see filtered ToDos? In this case, the server action should return data based on the search criteria but how do you return this data? The component with the todos should not fill by a full db search now, it should fill with the results of the sever action. You have to use the search term from the form. I am missing something here and I cannot do it (for the moment). Also, I am not sure any more which component should be a server component and which one should be a client component. Is my approach wrong? Are server actions only for mutations? Any suggestions? (All the videos show server actions mutating data. I want just a search) Thanks...
@SEOPro
@SEOPro 2 ай бұрын
Can we server actions pass data between components? for eg: if add to do is in one component and display form is part of another component.
@user-jr8kk1qb7c
@user-jr8kk1qb7c 23 күн бұрын
would useOptimistic still work if part of your form data is an image /videobeing uploaded to s3?
@edgararrizon5736
@edgararrizon5736 8 ай бұрын
if you could zoom out on your code a little more it be really helpful. great video and topic
@andresmontero7481
@andresmontero7481 9 ай бұрын
Amazing!! Great videos man. This may be a dumb question.. But let's say I want to pass in data that's not typed on an input tag, perhaps a Date from a calendar component. Could you add it as a prop to the addTodo action?
@AndrewAkaHrun
@AndrewAkaHrun 8 ай бұрын
I bet you can modify your formdata at your will before invoking the server action.
@zainyzain6471
@zainyzain6471 5 ай бұрын
we could use these server actions to api call like fetch text images and numeric data with out using api routes ?
@joerodrigo9661
@joerodrigo9661 8 ай бұрын
hi grad, what do you recommend partner for nextjs like for the backend? do you recommend like next + nest,prisma postgres? smtng like that.
@ByteGrad
@ByteGrad 8 ай бұрын
I would just try to stay within the Next.js system. Yes, I'd use Prisma and any of the popular databases are fine. Should be pretty easy to refactor it out into a separate backend once Next.js is too restrictive.
@adityaj21
@adityaj21 9 ай бұрын
should i dump all the api logic from route. ts to the server actions function?
@cubeunicorn4055
@cubeunicorn4055 10 ай бұрын
He boy, you tutorials are very helpful. Appreciate your work. When the react course will launch? Any date?
@ByteGrad
@ByteGrad 10 ай бұрын
Very soon, make sure you’re on the email list :)
@cubeunicorn4055
@cubeunicorn4055 10 ай бұрын
@@ByteGrad can you please give me a approximate time?
@ByteGrad
@ByteGrad 10 ай бұрын
1-2 months at most
@asadmehboob1300
@asadmehboob1300 10 ай бұрын
Please use react hook form with zod and Tanstack table
@mamlzy
@mamlzy 9 ай бұрын
​@@ByteGradyes react-hook-form and zod gonna be awesome🔥
@andyfifedenim
@andyfifedenim 9 ай бұрын
Just discovered your channel, thanks so much, each one i have seen is excellent.... i have a question, how do you authorize a user to use the actions? ie clerk auth?
@ByteGrad
@ByteGrad 9 ай бұрын
Thanks 👍 It’s a great question. I might make a separate video on this soon
@andyfifedenim
@andyfifedenim 9 ай бұрын
@@ByteGrad I would certainly appreciate the video.... in the meantime.....
@andyfifedenim
@andyfifedenim 9 ай бұрын
even following clerk docs.. i still get unauthorized...:(
@rjlacanlaled9419
@rjlacanlaled9419 7 ай бұрын
what do you mean unauthorized? if the session is active, your protected routes should be accessible (configured on the middleware file)
@hongz1
@hongz1 8 ай бұрын
nice clip. little bit hard to follow fast screen moving and talking.... Question. I noticed that they removed a word, "alpha" in serverActions documentation (but still under experimental). Do you know when it is going to be started officially?
@FrankyDeMeyer
@FrankyDeMeyer 9 ай бұрын
Fantastic video, thanks! One big disadvantage I see with server actions, is the following: in the future I might create a mobile app, to compliment my web app. Since I currently use API routes, my mobile app will be able to use them, the back-end will be ready. If I’d now convert my web app server actions (which is tempting) I won’t have any back end at all, Isn’t that a huge issue, do you think?
@riteshsingh1
@riteshsingh1 9 ай бұрын
True, This is the only reason, I am also avoinding this right now.
@Something9008
@Something9008 9 ай бұрын
Also, if you are self hosting keeping your server and frontend separate allows you to upgrade the VPS of each independently as production usage requires.
@tc5878
@tc5878 8 ай бұрын
Exactly. The curious thing is that I don't see anyone talking about this subject. In my world, rest api that feed multiple fronts are very common!
@wandreperes
@wandreperes 7 ай бұрын
awesome! good job! I did a project using the API directory and the handles to post/get/delete/… Also I used Prisma to database, and Zod, to validate, parse and transform the data. Client side, react hook form combined with Zod. Okay let's talk about what matters in my case! The financial institution send a webhook when the payment was approved to my API, and update the database… How to refresh the user interface in real time when the payment was approved without using a loop of requests? Websocket, okay. But in the nextjs 13 there is no a native solution for that?
@JoseAlejandroRR
@JoseAlejandroRR 8 ай бұрын
With many videos I have been totally agree, even keeping on mind your tips; however, not with this. This is one of the first reasons I started to leave PHP World, to work over monoliths is so hard to keep clean and handleable
@tomascarignano5002
@tomascarignano5002 2 ай бұрын
Si much value
@iamAmeeeeeer
@iamAmeeeeeer 8 ай бұрын
will these work in client components as well?
@codewithshriekdj
@codewithshriekdj 9 ай бұрын
actually i already tried the server action for the company i work in but it makes startup of our application very slow, mostly whenever we try to update the code of application we had to wait for like more than 20 minutes, and also you can't use turbo there. So I Suggest that Try to get form Data with Vannilla JS With An Hidden Input of Function Name and Send that Data To single api like /api/formsubmissions where the server function run there, for getting formdata use useref or 'const formData = new FormData(document.getElementById('formId')' and send that to single '/api/formsubmissions' via fetch
@sivadhanushuppalapati4041
@sivadhanushuppalapati4041 8 ай бұрын
please tell me What is the vS Code theme you are using
@mernik5599
@mernik5599 2 ай бұрын
Does anyone know if and how can we use useOptimistic for deleting items too? Like if I add a delete button in front of each of the items I want to quickly show the list with removed item
@ibraheemhaseeb3660
@ibraheemhaseeb3660 5 ай бұрын
So if I am using server actions, can I just call env variables like process.env.VAR or does that have some trick up it's sleeve as well. anyways, they are just redefining web dev. Not sure if it's a good thing or a bad thing. Feels like more ease for the developer but compromise on performance.
@wanarchives
@wanarchives 8 ай бұрын
is it same like in /app route? i thought its already server component, why still need server actions?
@appstuff6565
@appstuff6565 6 ай бұрын
useFormStatus minute doubt: Hey thanks for this, im just using a action = "/auth/sign-in" and rest all is same. But i do not get the "adding" state. what should i do?
@swartex92
@swartex92 7 ай бұрын
what theme do you have installed in VScode?
@ianc6418
@ianc6418 5 ай бұрын
very helpful! Except I can't import the experimental function like you did. I tried installing the experimental react and react-dom packages with npm, but I still get an error, and vscode doesn't seem to be able to populate it with autocomplete like yours did.
@ianc6418
@ianc6418 5 ай бұрын
I thought I replied to this, that function is no longer experimental in nextjs. they just haven't updated their docs.
@codeyalaya
@codeyalaya Ай бұрын
how to show #contact section of a long page, after submitting form using server actions with js disabled. #contact section is at last of the page.
@Vir7uaLGameplays
@Vir7uaLGameplays 2 ай бұрын
What about form validations? Like using zod?
@spencersnygg6966
@spencersnygg6966 3 ай бұрын
Do you have links to your code? It'd be nice to experiment with it to see if it still works.. i've studied so many tutorials from other yioutubers that didn't work because they used an element that was out of date before i found them.
@user-gq9vz9yg3q
@user-gq9vz9yg3q 3 ай бұрын
I have a form where I have "formsteps" (with values for type, name, placeholder etc) mapped out into inputs with dynamic values. This does not appear to work with the whole server action and FormData thing. If I just have a regular input that isnt mapped out, it works just fine. Has anyone encountered and solved this problem?
@Arunmurali12
@Arunmurali12 5 ай бұрын
I feel it's better to refactor the form alone to client component & perform all validations, interactivity, etc... Then create an api route to add the data... At this point the server actions part is making more work
@challengedollar2880
@challengedollar2880 8 ай бұрын
Hi ByteGrad. This is amazing. However, there is 2 minors issue that pertain. 1. How do you display the front end todos, splitting client and server? 2. How does one add a onClick functionality without breaking this pattern of code that you just described in this video? Thanks!
@aliahmedkhan9690
@aliahmedkhan9690 8 ай бұрын
That's the purpose of Next Server Components. The components will be rendered on server so you cannot use client events on it
@challengedollar2880
@challengedollar2880 8 ай бұрын
i made it work but okay. @@aliahmedkhan9690
@Oxeedious
@Oxeedious 5 ай бұрын
Somehow I got these PHP vibes while watching this
@Wilmar06210
@Wilmar06210 3 ай бұрын
Hello nice video, i have a question why would this form work (10:03) with JS disabled ? I am not sure to understand
@davidlin1980
@davidlin1980 3 ай бұрын
I believe it goes though the standard form post action. (I.e. form is posted to an URL, NextJS intercepts it and route it seemlessly to the server action )
@nisabmohd
@nisabmohd 8 ай бұрын
But when you use client components and make api call then when api responds success we just need to add that new data to state, where as in server components we are making a api kindof call and refetching the data that means an extra db query
@juviess
@juviess 7 ай бұрын
But what about client-side validation with zod for example?
5 ай бұрын
I tried to use revalidatePath from the API handler on PUT method - does not work. Updates only on page refresh
@chicagoboy279
@chicagoboy279 2 ай бұрын
is this only for forms?
@jeremyh8965
@jeremyh8965 9 ай бұрын
Why does useFormStatus need to be extracted in its own client component? My form is also a client component but it won't work if I call useFormStatus inline, it has to be extracted into its own component as you demonstrated in the video, and then it works. Also, it looks like the button component you extracted isn't flagged as a client component so I'm not sure how you were able to get it working. The latest version of Next calls for useFormStatus to only be used within a client component (it'll throw an error stating this).
@ByteGrad
@ByteGrad 9 ай бұрын
Probably some technical reason for being able to detect within which server action it’s being used. Button component is a client component because it’s being imported into another client component
The 3 REAL benefits of Next.js Server Actions
12:11
ByteGrad
Рет қаралды 22 М.
All 29 Next.js Mistakes Beginners Make
1:45:10
ByteGrad
Рет қаралды 43 М.
[柴犬ASMR]曼玉Manyu&小白Bai 毛发护理Spa asmr
01:00
是曼玉不是鳗鱼
Рет қаралды 25 МЛН
Don't eat centipede 🪱😂
00:19
Nadir Sailov
Рет қаралды 22 МЛН
小路飞姐姐居然让路飞小路飞都消失了#海贼王  #路飞
00:47
路飞与唐舞桐
Рет қаралды 90 МЛН
10 common mistakes with the Next.js App Router
20:37
Vercel
Рет қаралды 171 М.
Why I don't use React-Query and tRPC in Next.js
18:58
ByteGrad
Рет қаралды 67 М.
React Server Components: A Comprehensive Breakdown
52:42
Theo - t3․gg
Рет қаралды 89 М.
You might not need useEffect() ...
21:45
Academind
Рет қаралды 141 М.
NextJS Tutorial - All 12 Concepts You Need to Know
44:38
ByteGrad
Рет қаралды 219 М.
React + Servers = Confusion
20:30
Theo - t3․gg
Рет қаралды 39 М.
[柴犬ASMR]曼玉Manyu&小白Bai 毛发护理Spa asmr
01:00
是曼玉不是鳗鱼
Рет қаралды 25 МЛН