Server Components in React (Simple Tutorial)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to introduce the concept of server components in react and you're going to learn everything that you need to know to be able to start using them in your own applications we're going to go over and learn about server components and how they work the differences between them and client components talk about when you should use which and more importantly how to combine them together and finally go over some of the benefits and drawbacks of using server components as opposed to client components and also by the way before we start if you want to learn react by building a real world Project Check out project react it'll be the first link in the description all right so server components let's talk about them now probably you've already heard about server components and what they are from nexj last year nexj made a pretty big update when they launched the new app router that also introduced support for Server components now contrary to what it might seem server components are not specifically a nexj feature they're actually a react feature next ja just happen to be the first ones to properly Implement them now this this made quite the big news in the development Community because server components are fundamentally different to how client components work and how we were building with react all of this time traditionally react applications were mostly on the client this meant that to have an application running the browser would have to download a JavaScript bundle that contains all of the code for the application to be able to run server components on the other hand change that completely they literally add a new dimension to react and allow react to run on the server without necessarily being sent to to the client this is a fundamental shift in the way that react works at its core and how we use it to build applications so it's very important that you watch this video and that you watch it carefully and until the end because this will teach you how to be ready for the future of react so here I have a next just application that I'm going to use to show you how server components work we're going to be using nextjs because it currently at the time of recording this video has the best and most stable implementation of server components compared to other Frameworks it's also the easiest to set up now here we have have a component server page and this looks like a normal react component the only difference is that this is a server component and the reason why we know that this is a server component is because we are in nexj and in nexj all components by default if you're using the app router are server components unless explicitly marked otherwise which we haven't done now this component is a normal JavaScript function exactly as you would expect from a normal traditional react component and it also renders some jsx over here we have a main tag and then an H1 tag that says this runs on the server if we open up the application this is the component right here and we see that this runs on the server is painted on our browser and this component works exactly as you would expect I can add a period here and then let's add a period here and then I can go back and this is reflected in the UI again no surprises here this works exactly as we used to but make no mistake this has a fundamental difference than what we are used to although this runs and shows up on the browser the actual code that generated this HTML for the browser ran on the server and to really illustrate that to you let's now come back to our component and let's add some JavaScript into it so let's come here and let's add a simple console log in this component to track when this component gets rendered so we're going to do console.log and then we're going to put rendered like this now if we go back to the application and we open up the browser console and I can just refresh over here we're not seeing any logs in the console we're not seeing console log rendered in the console anywhere we're not seeing it because this is a server component it does not run on the client it does not run in the browser so how does this actually work how does a server component work while the server component has two parts it has all of the code inside of this return block over here djsx that gets converted into actual HTML and it also has all of the code here in the body of the component that is used to render that final HTML in the case of a server component all of this code over here actually runs on the server and then is used to compute the final HTML inside of here right this main tag all of it gets converted to HTML using this code as you would in a normal component and then that final HTML is the only thing that is sent to the client but it's sent as HTML not as JavaScript so this console log over here never actually makes it to the client it only runs on the server when this component gets executed it then computes the final HTML which has all of this over here and then this is what gets actually sent to the client and what shows up on the browser over here that's why we're saying that this runs on the server because the code that was used to generate this HTML only ran on the server and in our case the server is actually here if I open up the terminal this is the vs code terminal that is running the actual nextjs application you can see over here we have rendered right these are the console logs this doesn't log in the browser this logs in the server in the process that is actually running the react application and that is very important to understand because this is a fundamental difference to how a client component is going to work in the case of a client component this code would run on the browser you would see this in the console log if you open up Chrome and inspect the console you re see this log over there and then all of this code that is required to actually render this jsx into HTML also runs on the browser on the client everything runs there but in the case of a server component it doesn't and only the actual final HTML that is computed from that code is getting sent to the actual client to really see and understand how this works let's look at more examples of the differences between server components and client components so here if I go to the sidebar I have another component this one is a client component and the reason that we know that this is a client component is because here at the top we have use client this is how in nextjs you define a client component you put use client at the top and then this will mark this file and everything that it uses as a client component so then we have the same component over here it's called client page and this one renders the same jsx except that it says this runs on the client and this is just going to be a a normal client component as you're used to in react by now if we open up our browser again and we go here to/ client we can see that we have the client component and we have this runs on the client we can even come here and add console.log rendered and then we can see that this renders in our console because this is a client component and again all of that code happens on the client inside of the browser now let's say that we wanted to have a button here with an onclick event handler right so we can come here we can actually remove this rended here we can do button and then we can do click here for the name and just do something on click and then we can pass it a function that will simply do console.log and then clicked like this if you now go back to the application and refresh we can click this button and we have clicked log in the console this works exactly as we expect but now if you come here to the server component and try to do the exact same thing so I'm going to take this button over here and just paste it in the server now if you come here back to application and go back to server we're going to see that this doesn't work we actually have an error and we have event handlers cannot be passed to client component props in server components you cannot have onclick event handlers or any other event handler for that matter and just take a second to really think about why you can't do that in a server component you're running all of this code on the server and only the final HTML is what gets sent to the client so in that case a client cannot click a button because the code that is creating this button is not on the client there's nothing to click everything is happening on the server and once that is done then we get the button sent but this on click event handler here does not belong in a server component because this runs on the server not on the client and because of this you can't use onclick you can't use on drag Mouse over you can't use on focus on blur you can't use any of the traditional event handlers because they do not work on the server they only work on the client and for the same reason this also means that you cannot use any hooks either in a server component so you can't do something like use State like this you cannot do this in a server component because this won't work if I try to import this directly from react and save and then go back here to the browser we have a different error and it's saying here that you're importing a component that needs you state it only works in a client component but none of its parents are M marked with Ed client so they're server components by default you cannot use State because the concept of State the concept of something dynamically changing of a render cycle right which we have in act does not exist on the server because on the server all of this code is only executed once to generate the final HTML and then sent to the browser and that's it the component goes away it doesn't live to be able to have an update or to be able to hold State you also can't use use effect right this doesn't work because there is no render cycle in this component so there's nothing to trigger when the component mounts when the component updates or unmounts these things don't work if you want to have hooks if you want to have interactivity because all of these things really come for interactivity you have to put them in a client component just like this error is telling you it only works in a client component and but none of its parents are marked with use client use client once again is how you define a component to be a client component since we don't have this this is a server component and all of these interactive things just do not work now because of this you might be thinking to yourself well what's the benefit of using server components aren't we being limited by the fact that we can't have on click event handlers we can't have any hooks we can't do all of this stuff that we're traditionally used to doing with react what's the point of server components well yes it's true that when you're using a server component as opposed to a client component you do lose all of this functionality you lose access to the hooks to any event handlers and any interactivity which can feel limiting because it is you don't have access to these things but the question that I would ask is do you even need to have interactivity everywhere in every component in your application probably not and let me show you with an example so let's first get rid of all of this code over here and just make it fresh so we have no button we have nothing we're back to how we were initially at the start of the video let's take the common example of data fetching right data fetching is something that is very common in most react applications you're going to have to fetch data from somewhere and display it in your application now to fetch data in a traditional react client component here if I can just remove this what you would have to do is you would first have to do something like you state right have a state for your data so for example data and then set data like this and then we'll have to import UST state from react and then we might have a use effect for example use effect that would fetch the actual data so we can do something like this and then we can just import this as well obviously this is accounting for the fact that you're not using react query but even if you're using react query this is what react query does behind the scenes so the concept still applies now this is the way that we're all used to actually fetching data in react right you have a piece of State for your data and then you're fetching the data and once you actually have the data you're just setting it and updating that piece of state and that is going to cause the component to reender and then your data is actually displayed on the screen now this works fine but this is actually not the most efficient way to do things first of all you have to keep track of this state and you have to manage it then you have to keep track of a use effect and its dependency and we all know how complicated this dependency array can be and then you have to go in here and actually update all the things that you have to update and then if you want a loading state if you want an error State you also have to do all of these things here and manage them yourself not only that but all of this code can only run after the JavaScript bundle has been downloaded by the user on the client in their actual browser so you have to first wait for that to happen then you have to actually run this component without any data so this data is going to be undefined initially then you have to fetch the data you have to wait for the data to actually show up and then you might show a loading spinner while that happens and then you have to update the component cause a reender to actually show the data that's a lot of steps and this takes a lot of time however in a server component this looks a lot different so first of all because this runs on the server we actually get another benefit which is that we can make this an a synchronous function so we can do async like this and convert this component into an asynchronous function this works because this is a server component this wouldn't work in a client component and then because this is now an asynchronous function this means that we can actually do asynchronous stuff in here like fetch data from an API so we can do something like const data and then we can await and then fetch the data and then set it in this state over here this does exactly the same thing as we had in this client component we have the same data we're fetching the same data over here but the only difference is that now we're doing it in one line of code we have no state to manage we have no use effect to manage and more importantly we have no updates to happen we're just directly awaiting the result of this fetch storing it in this data variable and then we can directly use data inside of this component and the final HTML from the data from the fetch along with everything else is going to get built compiled and then sent to the browser to be able to show on the screen this is a lot less Cod than doing the same thing in a client component and is actually faster because this does not have to wait for the bundle to be downloaded in this case there is no bundle right we're not shipping any JavaScript we're only shipping final HTML to the client so we don't have to wait for any bundle to actually be downloaded which means that this code can run faster and then also we're not having to update anything and wait for something to fetch we're just waiting for this to fetch and then the data is immediately available to use in the component without having to trigger a rerender of the component so yes going back to the argument in a server component we we can't use State we can't use effects but we actually don't need to use them there's a simpler way to do it by just directly fetching the data awaiting it and then just using it in the component use effects and US state are a byproduct of having to use client components which have to wait and have to be run exclusively on the client and have to wait for the bundel to be downloaded before they can actually execute their code the only reason that we have to do all of this is because we are in a client component ideally if you're in a server component you skip all of that you ditch all of that and you just do it the simple way which is again a lot simpler and also there's another benefit so let's go here in the actual Explorer and I have here a expensive function file which is just a function that obviously is not really expensive but just imagine that this would be expensive that this had tens of thousands of lines of code or like imported some other expensive libraries and we wanted to use this function in both of these components if you come here to the client component and let's say we want to use it inside of this use effect over here we can do expensive function and call it like so because we've put this function now inside of this use effect inside of this component over here and we've imported this function inside of this component this function will now end up getting sent in the bundle that the user has to download on the client and if this is an expensive function if this is a lot of kilobytes of data we're now putting all of that data all of that constraint all of that load on the user to download before we can even begin to actually load and run the code in his client component but in the case of a server component if we were to do the same same thing expensive function and import it directly we're still using the function here just like we're using it in a client component we're still importing the function but because this runs entirely on the server this expensive function actually never ever makes it to the actual client there's nothing to download the cost of the expensive function of all of its resources is born by the server and not by the client so your users will see the same final HTML that yes now accounts for the expensive function but they are not the one running that function you are the server is which is more efficient now I hope that you're able to understand by now that there's actually a lot of meaningful benefits to using server components as opposed to client components now this doesn't mean that you should never use client components and that server components are the only thing that you have to implement from now on in youra application that's not the goal of this video and that's certainly not the goal of server components server components are not meant to replace client components but to actually live alongside them because the truth is in your react applications you're going to want to have interactivity you're going to want to have onclick event handlers you're going to want to have onchange event handlers and you're going to have to need to use UST state or use effect actually trigger some updates in your components you are after all building a react application which is meant to be interactive but the thing is you're not going to need that interactivity in every single component in your application there's going to be a lot of components that you don't need any interactivity and you can convert all of those into server components for the better performance and actually shipping a smaller bundle to your client to your users to make the application feel faster and more performant and the beauty of server components is that you can use them interchangeably with client components and actually get the best of both worlds when you need to have performance and run your code on the server with less code use a server component and when you need to have interactivity in your application you create a client component and you put all of that interactive code in there so let me now show you how to mix server and client components together so let's come here to the server let's actually remove all of this code because we won't need it we'll remove the import as well and we can actually remove the data here as well now we can close this and we can close this as well and here in the Explorer I have a component here I have a client component this is an empty client component and we know it's a client component because we're using use client here at the top to use this component inside of a server component the only thing that we have to do is come here to the server component and all that we have to do is just do client component and import it and place it directly in here and this works now the way that this works and this is going to be partly specific to nextjs is that first initially all of this code over here is going to get ran on the server initially once right including this client component so even though we put this as used client here nextjs is actually going to run all of this on the server once to generate the initial HTML to sent to the user but then because we marked client component with use client and it's now a client component nextjs is actually going to rerun this component once more on the client and this time it's going to add all of the JavaScript to make this component interactable and this is what we call hydration so in nexj specifically this works in two steps the first step is that first everything gets run once on the server including client components this generates the final HTML that gets sent to the browser and then every client component within it gets run a second time on the client to add all of the JavaScript in the process that we call hydration to make that component interactable right so if you go here to the client component and we just put some something client component in here and then we save and go back to the application we're seeing that we have one part that runs on the server and the other part that runs on the client in this two pass everything run once on the server and then this client component run once again on the client to make it interactable so this is how you put a client component in a server component now what about the other way what about putting a server component in a client component well you could do that but there's a little ashis because you have to be careful so here in the Explorer I have another component which is an empty component this is a server component without use client at the top let's now try to put server component inside of client component over here so we can take all of this code and actually replace it with server component like so now we've taken the server component and we've put it inside of this client component so this should work right well here's where you have to be careful because this doesn't work and the server component is actually going to end up running on the client even though we've marked it as a server component by not putting used client here at the top so why does this happen well it happens because of this use client over here so this use client doesn't only apply to the current page of this component when you use use client you're at the top you're actually saying and you're marking a boundary and you're saying that this file and everything Beyond is actually going to run on the client it's a one-way direction and you can't go back so what we're saying here is that we're saying that use client in this file everything that runs in here including these Imports should be run on the client right so the server component even though it's a server component it's being imported and used in a client component it will now run exclusively on the client and that's because of this used client over here so once again this does not only apply to this file think of it as a line as a boundary where you're saying that from here on now everything else Beyond this point is on the client and no longer on the server you cannot have anything on the server past this point in this file but now let me show you another way that you can achieve this and actually put the server component have the server component be rendered on the server but still show up inside of the body of this client component so first what we're going to do is we're going to remove the import of the server component we're going to remove this over here and we're going to Define some props for the client component so we're going to do type client component props and that is going to be children J react. react note and then we're going to come in here we're going to do children and we're going to do child component props like this and we're going to paste here the children inside of this client component over here so note we haven't imported anything in this component all we did is Define some props over here and still put all of this inside of your client for a client component then if we go back here to our server page component where we're actually using the client component now we have an error which is saying that property children is missing because we defined children but we haven't provided them so let's change it let's come here and Let's do let's close this client component tag and let me close it properly like so and then over here and now we can put in here we can do server component and import this directly so now what we did is we essentially have the same exact thing as we had it before we have the server component and we put it inside of the body of this client component but we did it through children this means that the server component is no longer imported in a client component file in a client component file it's now imported over here which is in a server environment so the server component is going to run on the server even though it's being used and plugged into a client component so what we have here is we have a server component that's run inside of a client component that's run inside of a server component you can do this you can mix and match but again you have to follow the rules and you have to be careful with this used client boundary because everything that you put in here is going to go on the client and to avoid that put it in a place where it's on the server and then pass it through children like we've done here and I know that this might seem a little bit confusing at least it was to me when I was first starting out working with server components but trust me on this if you spend enough time with it and you try to actually play around with it when this clicks you're going to realize that this makes a lot of sense and that this is actually a better approach to having everything on a client as we had it previously with react because now you're able to use this client boundary over here you're able to use this and Define exactly what runs on the server and what runs on the client you have the freedom to actually decide what is most performant for your app and what makes the most sense in this case we have no interactive code over here so all of this code should run on the server and it's going to be more performant for the actual user that's using our application but then in this client component let's say that we needed to have use State like this or or we need to have use effect like this we would put all of this code inside of this file inside of this client component This would run as normal as expected in your traditional client react application but without having to make everything in a server component in a client component sorry so we can use server components for their benefits get all of the performance and then when we need interactivity we create a client component and we actually put all that interactivity in there and everything just works beautifully this is a fundamental paradigm shift to how you use react components and where you define and how you build your application so once again it's very important that you wrap your head around this and try to play around with it to really understand how all of this works because this is the future of react and to help you with that so that you can actually get some practice because once again I really think that this is important all of the code that you've seen in this video is going to go inside of this repository and it's going to be linked in the description so all of this code over here obviously I'm going to C clean this up and make it just a little bit pretty so that you can work with it is going to be on the repository which you should definitely clone play around with it and really get a feel for Server components and how they work once again this is important and this is going to be the future of react and also if you're still here if you're still watching this video first of all thank you so much and second of all this probably means that you're really interested in learning about react and learning how to work with react which is great because I just launched project react which is a course where you learn react by building a real world project project I've literally poured my heart and soul into this course and this takes everything that I've learned over the last 8 years of working with react packages it in a course that's super easy to follow and that literally walks you through step by step with instructions and code on how to build a big and complex application with react from a toz if you want to check it out if you're interested it's literally going to be the first thing in the description it's called project react this is the best thing that you can do for yourself this is the best react course that you can take because this really is going to teach you everything that you need to know to be able to build a big and complex real world project with react so once again project react first link in the description I'll see you on the other side if you enjoyed this video and you want to see more videos just like this one make sure to leave this video a big thumbs up you can also click here to subscribe or you can click here to watch a different video of mine that YouTube seems to think that you're really going to enjoy and with that being said my name has been darus caen this is caen Solutions thank you so much for watching and I will see you in the next video Chia cha
Info
Channel: Cosden Solutions
Views: 10,538
Rating: undefined out of 5
Keywords: react tutorial, react crash course, react developer, learn react, react hook, react hooks, react hooks tutorial, programming tutorial, react hooks explained, computer science, tutorial for beginners, react component, learn programming, web development, frontend development, coding for beginners, simple code, easy programming, react, react native, server components, next js, app router, client vs server components react, client components
Id: ePAPd9qzGyM
Channel Id: undefined
Length: 25min 26sec (1526 seconds)
Published: Wed Apr 03 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.