NextJS 13 Tutorial - Routing, Data Fetching, Server Components...

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys how's it going I'm back here with another video and today I'm gonna be bringing this video where I'm going to be going over the new changes that come with the newest version of next JS I've been meaning to make this video for a while now and that's why I'm excited to bring this for you guys the reason why I waited a bit is because I wanted to let the changes marinate for a bit let myself enjoy them and understand everything properly in order to fully bring this video and I know you guys have been requesting this for a very long time now so if you want to check out the code we're going to be writing in this video I'm only going to be focusing on the new changes by the way so if you want to check out the code for that it's all going to be in the description and before we get into the video if you could leave a like And subscribe I would massively appreciate it because it would help push my videos to more people and that extra light that take you basically no time to to leave uh actually helps me massively and I would really appreciate if you could do so so with that in mind let's get into the tutorial [Music] [Applause] [Music] [Applause] okay everyone so let's start with the video so to start this off I really want to just first show you guys how to create a nexjs application because there has been some changes in the creation process so I wanted to show this to you guys so first of all you guys have to obviously install the create uh next app um a package inside of your system you have to install it globally and when you do so you just come over here to any application I'm going to be using yarn in this case but you can use npm as well of course I'm gonna just run yarn create next app just like this then it will ask us to respond to some questions and this is where some of the changes appears first of all I was going to say what is your project name so I'm going to put just a DOT over here because I want to create this project inside of the current directory that I'm in so I'll just press enter then it's going to ask us first of all do you want to use typescript for this project uh I'll say yes but I won't be focusing it on typescript at all would you like to use eslint I'm going to say yes Tailwind CSS let's say yes and then it's going to ask us if we want to use the source directory for this project so um currently with nextgs there's going to be a folder called the app folder and this can either be inside of the source folder or just as its own thing so I'm gonna by default it says yes so it will return Yes anyway will then ask us if we want to use the app router so there is two different types of routing that we can have in in xjs now the app router is a recommended as you can see over here and by default it says yes I'm going to show you guys how to work with it so I will press enter as well then would you like to customize your import Alias I'm going to say no and it's going to start installing all of our nextges stuff so I'll wait before I wait for it to finalize and I'll be back in a second actually while it is installing I'm gonna talk a little bit about um turbo pack which is one of the first changes that I wanted to introduce in this video for next.js13 so what turbo pack is is basically an alternative to webpack um so Nexus 13 now it's using a new build tool which is this one over here it was build this build tool turbo pack was completely built using rust as you can see which as you guys might know it is a very powerful and fast language and according to uh probably some research done by the next JS team and probably some research done by the turbo pack team this over here is 10 times faster than using Veet and 700 times faster than using webpack I personally haven't tested or try to Benchmark those numbers but I do believe them you can see in the turbo Pack website it does uh show a comparison of like how Nexus 13 um acts and how fast it is when using turbo pack compared to its other versions so like for different things that you can do um in your application like a cold sort it is way faster than the previous versions of nexjs including um the current version of Veet so it is a pretty good change if a nexjs application is built really fast and with a pretty efficient um service like this one over here so that was the first main change but it's not something that developers will really notice unless they want to make a lot of customization to their project I do think it will become hard as we as we go through because a lot of people are used to using webpack and also no one really knew turbo pack before this I like some people probably knew it but I personally never heard of it before so to make any changes or even just work with rust it will be kind of complicated however I do think um this is a step in the right direction it is way faster than webpack as they even mentioned it being 700 times faster than webpack is is outstanding so this was the first major change so the next uh change will obviously come with a code and as you can see we successfully created our nextges project and the folder structure for next.js is obviously pretty similar to how it was before we do have this Source folder and inside of it there's an app folder this app folder is where all of our application will exist right so we have over here by default we have a couple things right just a normal polar plate um like code when you install a create next App application I'm going to run this application and obviously to run apps in nexjs you just run yarn Dev um we'll hope that it will open up over here and as you can see on our locals 3000 we have our next application all right so what I wanted to talk about first is routing because this was probably one of the biggest changes and it's I actually really enjoyed the way that routine is done in xjs13 um so I wanted to show it to you guys so for first of all if you want to have routes in your application and to do that I'm actually going to come over here and delete all the stuff that I already came with next.js and let's create new routes in our app right you can see our app is completely empty right now imagine we want to create an about page right so if I were to do this in this version of nexjs I would create a folder called um about just like this right and then instead of this I would create a file called page.tsx now I'm using typescript here if you're using JavaScript obviously call this page.gsx however it is important and really important for you to call it page because this is how nexjs will identify that this is supposed to be a page a route and the way they're gonna get the name of the route is based on the folder as you can see over here so over here I'll just export default um like this default function and then put the name of a function we can call all of these functions just page if we want to but we can also call them about and I would call it this way because um I do think uh it matches it's easier to search for code later on if you're calling it specifically what the page is about but in this case we'll just keep it like this and then obviously return some sort of UI I'll return like a div and inside of this div I'll put a header tag saying this is the about page then if we save this this is done it we don't have to handle any routes anything like that we don't have to create an external folder just to keep all of our routes everything is created this way we can just come over here to our code and go into the um about route just like this and you'll see that it is displayed exactly what we put on this file so this was a major change into um next.js it isn't it's just a different way to approach this and we obviously with Nexus we even in the previous versions we didn't use something like react right or done there was already some built-in running system for it however it's just some changes that I think are pretty cool especially because there's a lot more than you can do with this like if you wanted to create a nested route right so if I wanted to say um I want to build two different routes that are extensions of the about route I would come over here and create a folder called for example imagine we want to have a website where it's it has an about page but in that about page it can either be about us or about someone else right I could create about us like this and about someone else or I'll just say someone and those are two different routes that are going to be nested inside of the about route so I'll just put over here page.tsx like we did before and hear the same thing and then um we would obviously just come over here and copy this code and Export some sort of component inside of this ones uh so say this is about us page you know about someone um else page and this one is the about us page and we can change this to about us and this one to about someone else now just like that we can come inside of our website and if we'll go to the slash about Slash us you'll see it will say this is the about us page and if we went to slash about Slash uh someone you'll see that this is the someone else page so it's that simple no extra configurations it's all done like this so obviously if you wanted to do something like use Dynamic routes like have some sort of params all we'd have to do is inside of like for example other Bob Page imagine we want to have an ID or something like that I would create a folder called ID just like this and then instead of here I would create obviously again the page.tsx and copy all of the code that we had before but now let's call this about with params or with ID so now we can get some ID from the params right from the URL and to get those params I'll just grab them from the props just like this and then we can come down here and say that this is the about page with uh ID equal to let me grab the params and say dot ID because we have to this will be an object and ID will be the variable that we're trying to get from our params so say something like this and this is typescript so we'll be complaining about this so I'll just set the type to any for the purposes of this video then if you come over here and we try to go to the about page slash Five you'll see that it will say this is the about page with id5 if we went to about Slash six it would change to six so this is dynamically changing based on the URL I do think it's screwed up with uh no you didn't it still set us up you see that although we have programs for the about page it doesn't mess up the other routes the other nested routes that we also had inside of this application we can still access the US Route and the someone wrong there is more to rounding that changed as well but I will introduce the other stuff later on in the video uh because it will correlate to what we're talking about in that part of the video so now what I really want to talk about is a little bit about layouts which is actually pretty cool it's something that you can do to establish the structure of your website so you see we have over here A bunch of routes right we have the about the about us the about someone we have a bunch of routes that technically if you're in the home page they can't be accessed right and the normal thing to do would be to create a nav bar for this but where would we put the number well I'll create over here just a simple navbar I'll create a components folder and create a navbar component so I'll say something like navbar dot TSX here I'll just export that Network component and here we can just fill this up with links uh which are actual components from next.js but we can just import it by saying import link from next slash link like this and we can just use it over here I'll just create a link for all the routes that we have so far so we have one for the about uh we have one for the about us and one for the about someone else obviously it's more common to have different routes not not all routes about being an about page but then in the link component we can just put an href which is going to be the link to where we want to go so obviously I want to go to slash about here I'll do the same about us and hear the same thing so now we have this navbar right but how do we display this navbar inside of every single component we want it to be above over here no matter the route we want to have access to this nav bar in every single route in our routing system so the way we do it is we come over here to our layout.tsx file and here we have a lot of really cool information so the root layout is a function which we can use to determine how we structure the actual HTML of our website in the sense that over here in our body we have the children which is technically all the routes that are being displayed all the components that are being displayed will exist inside of here but if we want to put a nav bar that is rendered above the all of the other routes so it's always in the website no matter what we can just put it over here just like this and you'll see that no matter what this uh nav bar is appearing and if I click on this it will keep changing the routes as you can see right I didn't put actually one for the home page I'll do that really quickly right now by just saying home and doing this so it's really cool right and we can do we can do a lot of stuff with this we can actually also add a footer right I'll just add a a text called footer but you'll see that this will also appear at the bottom of the website no matter which route you are in so this is a really cool thing the root layout and there's more to this file specifically that I can I want to talk about but I'll talk about later on in the video especially the part related to metadata and the reason why I want to keep that a little bit to the side for now is because one of the main changes with nextges is the way you fetch data and it's actually extremely important and I really appreciate the changes that they made because I think it will make next chance easier simpler and more efficient in the long run so first of all uh I assume you understand the distinction between a client component and a server component obviously with next.js as a whole one of their main the main reasons why you would use nexjs is the fact that it allows us to have server side rendering which has a lot of benefits which have been talked about endlessly in the past the fact that with server-side rendering you have uh you facilitate search engines to find your website due to the fact that the Bots and website crawlers that are trying to find keywords in your website they're able to find what your website is about when you have server-side rendering because with client-side rendering which is what normal create track tab for example does is it has an empty HTML file just a single HTML file and when you enter the website it will download all the JavaScript and that JavaScript will put all of the keywords and information that your website is composed with inside of that HTML file so by default before you get into the website there's nothing in the HTML file which means that website Bots like a search engine Bots will won't see anything in the website and that website won't rank higher in something like Google right so server side rendering prevents that and also on top of that because you don't have to download all the JavaScript immediately when you enter the website there's that extra efficiency in the beginning right so that's something really good of about server components and server-side rendering as whole and now by default all of the components and next.js are server components this facilitates notation in my opinion with previous versions of an actions you had to use functions like get static props and get server-side props but we don't have to anymore and that's something that I know people in the past when I made videos about xjs I always complained that they didn't really understand what was happening so now the notation is completely different and I think it's pretty well maintained now it's pretty well it's self-explanatory now so as an example over here I'll create another route and I'll create it um a route called list of posts and this route will include we're going to make an API request to an API which will give us information about posts like posts on Instagram or on Facebook so to do that we'll come over here and say page.tsx just like this and again export everything uh wait let me just copy one of the pages and Export the component let's call this list of posts just like this and let's add the list of posts to our navbar so I'll just grab this uh call it probably just posts and change the route as well so what we want is to make an API request to this API which I'll leave the link in the description it's a free API which just gives us like fake data so we can test inside of our projects and the way we're going to do this is we actually can create a function up here called get something like get uh posts data just like this and we'll make this function be asynchronous because obviously we're making a request using the fetch API so we'll come over here and say const res to get a response from the API request we'll say a weight Fetch and we'll put the link to the API inside of here like I said I'm using this API called Json placeholder typicode.com I've used it in the previous videos I think they're pretty good because they just it's pretty simple and easy to just test their endpoints and I can get a list of a couple posts which is pretty nice but I'm going to get the response and I'm going to return like this return res dot Json now how do I access this data inside of our application well since this is the new version of nexjs what I can do now is I can actually make this function be asynchronous so like the component is asynchronous which is something that we haven't seen previously as as being used as notation and react and over here if I want to grab the list of posts I'll shape posts equals to a weight get posts data just like that and we have access to this post and obviously we can just Loop through it because it will be a list so I'm going to say map and then post and I believe it each Post in this API just has like a title so I'm going to say uh just return back uh some sort of like paragraph saying the post dot title and this is typescript so it will complain I'll just say but this type of this is any and whatever let's check to see if this is working I'll go to the posts and you can see a list of posts is being displayed in our screen so as you can see we were able to fetch our data in a server component without having to use the previous notation that we had before and this is great because we can actually fetch multiple data at once like I can actually create another function over here and try to get user data right so I'll say users data and this API does have a user's endpoint as well so let's try to get both of them at once the way we're going to do this is actually I'm going to say promise I'll actually the notation to get two pieces of data at once is we'll first try to get the posts and then the users as an array like this and then say promise dot all and over here we'll have an array just like this and we can put the um the functions over here to request the data in the order that we want to receive on the left so we're fetching two different apis or two different endpoints in the same server component um and receiving all the data in minimal amount of code right it's it's actually pretty clean the way it writes right now so actually with this users I don't want to display them I'll just console log them so you guys can see that it's working we'll see over here we'll refresh we still get the post data which is good because uh it means that that request is working and with the users I'll just actually display them over here at the bottom I'll just add a list actually I'll just display their names like this I'll have a div and I'll just Loop through the users.map I'll grab each individual user like this and then return over here again the P paragraph and displayed the user probably just get the name of each user if we do that and I also set the type to any we should check over here to see if both requests were done uh I think they were because you can see at the bottom of here I do get a couple names of people and it is 10 users that are returned in the API so it is working right we get the posts and we also get the users now there's a lot more to this so this being a a server component there's a lot of things that we can do and a lot of things that we can do I would say a server component would be mainly used for for example fetching the data right uh just like we're doing over here because you can't use some of the um stuff that you can do with the client component for example over here I can't put a button right I can't I can't put a button obviously but like I couldn't come over here say click me and put an on click over here because this wouldn't be part of what a server component can do this is like a browser uh this part of the browser API so if I were to do something like this you'll see event handlers cannot be passed to client component props because uh over here we're not inside of a server component because over here we are inside of a server component so not a client component and there is a distinction between both of them so you can't do something like this server components are meant to be run on the server right it's the whole purpose of it so um you can't have browser stuff in that but um you can work around this in the same way that this can't work in uh in a server component you can't also use stuff like use effect and use state or any any client-side Hook from react instead of this kind of components it would just tell you the same error message so you have to be able to understand the distinction between what are the purposes of a server component and a client component and I'll show you guys also how to fetch data in a client component in a second so one important thing to notice is that since this is a server component and the way that they behave is the fact that when you fetch data like this all of the data is being cached static so we this is almost like by default we're using a get static props which is one of the the ways we fetch data in the previous versions of nexjs and with this the data is all cached static which means that um it wouldn't be good for a use case such as one where the data is constantly changing an example would be this API I found which fetches data random photos of dogs so it constantly gets randomized right so you do need to whenever you refresh this page or whenever you load this this component you want to fetch this data again so this over here specifically is something that uh I would probably require this to be not static so what I want to do over here is I want to create a new const a new function and let's say get dog data just like this and I'll put this API over here and the difference is the way we actually structure this because if I were to just put this over here just like this and we're to also get the dog uh so I would just put dog over here and put the get dog data function over here if we were to do something like this and we were to display the picture of the dog so I'll put image which by the way the way you you work with images in xjs would come over here at the top and import uh the image component from next slash image just like this and if we were to display this we'd come over here just play the image component and pass in uh some information for example the dog URL if I check the actual API you can see that it comes with a message which yeah the message is the actual URL so what I'm going to do is I'm going to come over here say image past the source of this image and the source will be the dog Dot message just like this if we were to display something like this uh oh yeah it's asking us for an ALT uh it's just for purposes of obviously accessibility I'll just say dog just like this save this then you'll see that over here it is missing okay it's missing the width and the height okay yeah it's just because the image component is kind of annoying sometimes so I'll say 300 and the height is 300 as well so let's check to see the API working oh yeah this is actually something I forgot to tell you guys which is actually really cool that it happened because it is important for you guys to understand uh with nextgis what you have to do when you have images that are from a different website so like from an API for example you have to set up that it accepts that domain inside of your next dot config.js file so we have this object over here I would put images just like this and then I would say domains and this would here include an array of acceptable domains so in our case the domain we want to accept is images.dog.ceo right so I'd come over here and say images.dog.ceo and I believe that this would work as you can see but it's a missing required components okay it still worked as you can see so we do have to specify which domains are we accepting is for security reasons obviously uh we don't want to be accepting uh stuff from other domains without actually specify which ones we trust but in this case with the trust this API and we do have to configure it this way so we over here have this picture right and it's working perfectly but what we want is to whenever we refresh the page to change the picture because this API returns a different picture every time you fetch its data but since by default the fetching is static you see it is caching the data and it's just showing the same image but if I want to change this image so request this every time the the component or the page is reloaded we have to come over here and at the top uh where we make the get dog data we add this object called obviously the cache we set the cache to be equal to no store and this will allow us to refresh the page and make the API request again every time we refresh the page which is perfect for us now there's even more that we can do with this for example revalidation you can come over here and set a property called Next which is obviously just existent in xgs in this property we can put a validate value now what this will mean is we can reevaluate what the request is at a certain interval so for example if you're over here and we want to fetch this dog data but we want to keep like we don't want you to keep fetching if you keep refreshing your page we actually want uh if you refresh your page a bunch of times in a quick succession we want to keep the same image maybe you're refreshed by mistake and you want to still keep the same data that it was before so we can set an interval over here of how many seconds we want to actually fetch the data again so make another request so if I were to come over here and put three seconds you'll see that if I come over here and I refresh the page we have this one but if I keep refreshing only after three seconds it will actually fetch a new dock so just to again show you example I'm going to refresh the page it's gonna show me a picture of a new dog but I'm going to keep clicking refresh and you'll see the picture won't change but after three seconds I shall give myself more time I'll give myself 10 seconds so let Let's test this I'll refresh this over here we'll see a new dog I can click refresh and the dog won't change it will only actually request after 10 seconds as you can see so we got another dog I can keep refreshing it won't change but after a while like 10 seconds uh uh it hasn't passed in seconds yet you'll see I'll get a new dog but this dog for some reason the image is not displaying but yeah you get what I mean right this is what the revalidate actually does now a cool thing you can also do with um fetching data which I've actually mentioned that I was going to show it to you guys it's related to routing as well is the fact that we can actually create what is known as error and loading components inside of each page so we have this list of posts page right imagine that there's an error in any of this actual um like apis right for example imagine this one over here the guest post data I were to just delete this and obviously this will throw an error because it should throw an error right this is not a legit API to be fetching data so as you can see over here it will give us an unhandled runtime error because there was an error in the fetching now we don't want to see this right we don't want to display this to the users we want to display a customized message saying that there was an error now the way we do this with this version of actions is we can actually just create an error.tsx file inside of this route and then obviously copy the the component there was an error loading the data or something like that right and um to make this work this has to be a client component it can be a server component because obviously why would we this be a server component if it's an error message there was an error fetching in API we don't want to fetch data inside of an error component right and you'll see that this will actually not work it says fail to compile which is a different error message because now it is trying to display our error component that we just created but we need to turn it into a client component and not a server component for require by default all components in next.js13 are server components and if you want to turn them into client components meaning that are components that you can I don't know use the on clink method or use use State and use effect you just come over here at the top and say use client just like this and now this will work so it is infinitely doing something so as you can see and now displays the error uh message now it's infinitely trying to uh fetch the data which is something we definitely don't want so I will come over here and actually replace this back to what it was before but one thing that is actually cool as well is that there's also a loading component that we can put you can just come over here and say loading.tsx and I'll just copy what we put in the error page paste it over here call it loading and let's say that while the data is loading I just want to say loading dot dot dot now if we were to save this you'll see that if I refresh this for a brief second it should show loading but I do think it takes actually a longer time to load so what I'm going to do is I'll remove this over here and I will remove this as well and just make this be cash no store like it was before so this has to refresh every single time this I'll remove I'll remove this as well we'll just have to dog into this API so that means that technically we just have to say that const dog is equal to a weight get dog data and then I'll remove all of this and just keep the dog image being displayed so now if I were to come over here in order to refresh this you should see a loading state for a few seconds and then the data is fetched so the learning component is indeed working as expected so now that we've gone over everything that I had to say about fetching um I want to revisit the idea of server and client components because I do think it's a major change not only in xjs but it was a major change in the latest version of react as a whole reacting team with introduction of server components and I want to explain because this use client thing is is just a small step in in this whole Deep dive that you can have in this whole pool of information on this new way to structure your next.js applications so the idea is that obviously the difference between a client and a server component is that a client component is main its main purpose is to act as a intermediate between the user and the actual client in the sense that inside of the client components you can do stuff such as um browser events and react Hooks and react not logic stuff whilst on the server components it allows you to render your components your react components in the server which further decreases the amount of JavaScript that you have to send to the client and load in the client so it's a it's it's just that both of them have different purposes and just the way the react was before where all components were completely rendered in the client um it made it such that you can be as efficient as possible by just dividing your components into server and client components now there there's some rules that you have to follow if you're going to use a server or client component in nextges so like I said there are a couple rules that you have to follow when dealing with server and client components first one is you can't import a server component into a client component so that's that's straight up a rule that you have to follow but you can pass a server component opponent as a prop or a children to a client component so so in order to know when to use each of them I would say this is a pretty good overview like you would use your client components when you want to use react hooks when you want to use browser API stuff like event listeners and and stuff like that which is a lot whenever and whenever you're using a custom hook or depending on like the life cycle methods of your react application and you want to use a server component whenever you're passing sensitive information such as like API keys and stuff or when you're making like API requests such as that and when you need to access backend resources directly which again relates to everything I mentioned about fetching data and when there are large dependencies because again remember you wanna you don't want to just make all your components server because I don't even think you could build a website directly like that unless it's just this plain data and not having any in interactivity um and you have to know that there are benefits of using client components as well it's not just server components are the best thing in the world they are going to help with maxjs applications and react as a whole and I think they're going to stay here for a very long time but it is important to understand when and where to use them so this is basically it there were new changes that I didn't uh talk about but because I think this one this one's over here are the main ones I am going to make a video on SEO like how SEO changed in Nexus 13 probably this week um so I'll be talking about the metadata API a lot of those stuff you want to check that out I'll probably link that video when I post it to this video but this is basically it for the video I'm really enjoying xgi so far I know it took me a while to make this video but it's just because I was really trying to internalize everything and learn everything as as at my own pace also you guys know I had a lot of work this semester graduating and finishing my studies and I'm happy to be making exercise content because I will be releasing an xjs course for beginners like straight up I'm not assuming you know react I'm not assuming you know anything it is a full-on nextges course that I will be teaching to you guys so stay tuned for that it will be my first uh paid course that I've ever made other than the ones I've had on on other platforms but it will be fully mine so uh it won't take away any time from the videos I'm making currently um it's just on top of that and I'm really excited to do that so thank you for watching the video If you enjoyed it please leave a like down below and comment which you want to see next subscribe because I'm posting twice a week and I'll be massively appreciated and yeah that's basically it really hope you guys enjoyed it and I see you guys next time [Music] [Applause] [Music] [Applause] [Music] thank you
Info
Channel: PedroTech
Views: 18,084
Rating: undefined out of 5
Keywords: computer science, crud, javascript, learn reactjs, mysql, nodejs, programming, react tutorial, reactjs, reactjs beginner, reactjs tutorial, typescript, react js crash course, react js, node js, express js, pedrotech, traversy media, traversymedia, clever programmer, tech with tim, freecodecamp, deved, pedro tech, nextjs, next js, nextjs 13, next js 13, nextjs tutorial, nextjs 2023, next js tutorial, nextjs data fetching
Id: 8pzIuLFuv6U
Channel Id: undefined
Length: 36min 52sec (2212 seconds)
Published: Wed May 24 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.