How To Use Pre-rendering and Data Fetching - a Next JS Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign documentation Nation welcome back to our next JS series we are picking up right where we left off with pre-rendering and data fetching we have already covered the introduction setup and Link component and utilizing CSS within next.js framework so if you haven't seen those already I'll link up top to the playlist so you can go ahead and catch up with us and uh so far looks like we have 260 points so we're rocking and rolling over here re-rendering and data fetching we'd like to create a blog we have the desired result which we looked at before but we'll open this up again why not here's our sample blog but so far we've added no blog content in this lesson we'll learn how to fetch external blog data into our app we'll store the blog content in the file system it'll work if the content is stored elsewhere like a database or handle CMS things will learn in this lesson we're going to learn about next js's pre-rendering feature the two forms of pre-rendering static generation and server side rendering static generation with data and without data get static prompts and how to use it to import external blog data into the index page and some useful information on getstatic props I'm excited let's go we're continuing from the previous lesson we are if you are not there is some instruction here about now letting start a code which solicit is optional I guess because we are continuing the previous lesson right so go ahead and catch up with us with that download and we're rolling right along re-rendering before we talk about data fetching let's talk about one of the most important Concepts in next.js pre-rendering my default next JS pre-renders every page this means that next.js generates HTML for each page in advance instead of having it all done by client-side JavaScript pre-rendering can result in better performance and search engine optimization each generated HTML is associated with minimal JavaScript code necessary for that page when a page is loaded by the browser it's JavaScript code runs and makes the page fully interactive this process is called hydration so there's a paragraph here about how to check that pre-rendering is actually happening I'm just going to go ahead and trust that it is and not run through the steps but if you'd love if you'd like to do that go ahead let us know in the comments how that worked out for you if your app is a plain react to JS app without next JS there is no pre-rendering so you won't be able to see the app if you disabled JavaScript for example enable JavaScript in your browser and check out this page yeah I'm I'm good I'm I understand this I don't want to experiment with it I want to just continue on with learning this framework graphical summary here is nice though huh pre-rendering using xjs pre-rendered HTML is displayed and then hydration react components are initialized and app becomes interactive no pre-rendering if there's no JavaScript Nothing's Gonna actually render which of the following is not a benefit of pre-rendering we know there's improved SEO we know it allows your application to work without JavaScript at least immediately right pause your application to only runs server side which is not a thing that they have told us about this yet so we're rocking and rolling keep going please bring me to actual stuff soon re-rendering and data fetching two forms of pre-rendering xjs has two forms of pre-rendering static generation and server sign rendering the difference is in when it generates the HTML for the page addict generation is the pre-rendering method that generates the HTML at build time pre-rendered HTML is then reused on each request server-side rendering is the pre-rendering method that generates chtml on each request so let's see if this helps us out a little bit with our understanding here static generation on the HTML is generated and build time and is reused for each request right so we have our build next yes builds the application for production HTML generated and then reused for each request to that server from our individual clients over here server side rendering the HTML generate on each request so a user has a page request it hits next.js HTML is generated and sent back to the user I don't fully understand the point of having this twice but okay I think we understand the cycle here right so we have pre-rendering and development mode and going into production static generation will only happen once at build time not on every request okay our page basis importantly next.js lets you choose which pre-rendering form to use for each page you can create a Hybrid next JS app when using static generation for most pages and using server-side running for others okay so we know it does both things we know we're going to have the ability to choose which it does and when this this is the thing that I think is going to be the most valuable to us and learning this framework is when to use static generation server-side rendering the previous explanations gave us an idea of what that's all about but I don't know just knowing the definitions what what really makes sense to do so the next JS team recommends using static generation with and without Beta whenever possible because your page can be built once and served by CDN which makes it much faster and having a server render the page on every request you can use static Generations from any types of pages including marketing Pages blog posts e-commerce helping docs you should ask yourself can I pre-render this page ahead of a user's request if the answer is yes then you should choose static generation on the other hand static iteration is not a good idea if you cannot pre-render a page ahead of user requests maybe your page shows frequently updated data and the page content changes on every request in that case you use server sign rendering be slower but the pre-rendered page will always be up to date or you can Skip pre-rendering and use client-side JavaScript to populate frequently updated data okay so maybe this is something like if we have like a I don't know a stock ticker or something daddy generation isn't a great idea right because that's going to be something that's going to be constantly updating data so if we have static generation that might be out of date something similar I don't know I wish I wish it would give me more in-depth examples here great to know the things that I can use to add a generation on but give me something as an example of what I really shouldn't be using it on but I think we should get the general idea right and also I don't know if you're going to try and error this stuff too right if you were a static generation or if you're if you choose service on rendering and it doesn't do what you need it to do and you do static generation and also I think that might have to do with like Circle loads and things like that too right do you really want server-side rendering for the majority of your stuff and more communication with a server probably not we'll focus on static generation in this lesson we'll focus on static generation on the next page we'll talk about static generation with and without data okay when would you use server sign rendering you have thousands of pages when the data needs to be up to date with every request when you are building a page specific to a user well we already know when the data needs to be up to date with every request that is basically when we want this right that's what it fills us up here it's not a good idea uh if you need frequently updated data correct good job we're learning oh I want to code maybe we'll get there soon static generation with and without data static generation can be done with and without data cool I I can't I can't not giggle with some of the repetitiveness of like here is the title and then the first sentence is exactly what the title is so far all the pages we've created do not require fetching external data those pages will automatically be statically generated when the app is built for production okay so I don't get the choice there if I'm not fetching data it's just immediately static which is fine right I think that's good optimize that for me don't make me think about it set a generation without Beta or pages that can be generated but not fetching external data at build time xjs build DM for production HTML generated no fetching cool however for some pages you might not be able to render the HTML without first fetching some external data maybe you need to access the file system fetch external API or query your database at build time xjs supports this case static generation with data out of the box I don't know he's telling me a whole lot on on the capability without really giving me a work for the examples right I feel like I'd I'd rather do this in reverse order I'd rather work for the examples first or see some of this in action and then kind of dive into what what all this text is I think I would have a me personally A Better Learning Experience getting the Hands-On and then kind of reading the theory and and going through the text and document more so static generation with data using get static props how does it work well in next.js when you export a page component you can also export an async function called get static props if you do this then that setup props runs a build time in production and inside the function you can fetch external data and send it as props to the page so here we have our first actual coding example export default function home and there's props and then whatever our code is going to be here export async function get static props get external data from the file system API and database Etc we get our data back from whatever our API call is or whatever our external fetch call is return props the value of the props key will be passed to the home component okay maybe it's just me I don't love examples like this that are just kind of code in space um yeah cool I can I can start to understand the concept but until I really know what's going on around this code and how this is even living in an application I'm really confused about what this is going to be essentially get static props allows you to tell next.js hey this page has some data dependencies so when you pre-render this page at build time make sure to resolve them first development mode runs on each request okay so let's use get static props yes if it's easier to learn by doing yes why both the trouble of telling me all this stuff first and then tell me exactly what I wanted to do in the first place so start from using the next page we'll get static prompts to implement on on blog okay I'm like 15 minutes in and I haven't done anything except for read out loud it sucks the blog posts in our example will be stored as local markdown files in our applications directory not patched from an external data source so we'll need to read the data from the file system in this section we'll go through the steps of creating a Blog that reads markdown data from the file system cool this is a little bit repetitive but we're there creating the markdown files first create a new top level directory called posts this is not the same as Pages slash posts in your root folder okay and then we're going to create some two two markdown files so in our root folder which is this mix.js Dash blog we're going to create a new directory all posts and then within there we're going to create two Files free rendering markdown and ssg-ssr markdown now copy the following code to the pre-rendering file boom there's our beautiful markdown and here's the one for the SSG SSR and we can see these are the two posts that we have here and this is when to use static generation and this is the two forms of pre-rendering those posts that we've got on our example you might have noticed that each markdown file has metadata section at the top containing title and date this is called yaml front matter which can be parsed using a library called a gray matter or we're going to install gray matter cool let's do that so we're going to open our integrated terminal here with control tilde is the keyboard shortcut first install gray matter which lets us parse the metadata in each markdown file is this the only thing this thing does not familiar with what this is of course front matter from a string or file okay cool what does this do I see so this is basically just going to turn our markdown file into an object which is interesting because I was already getting confused of like why are we using a markdown file to like how am I going to work with that when we when we do some data manipulation here but this makes a lot of sense right okay got our terminal open npm I gray matter oh you know what I am not in my root let's actually get into our root here and now we can do it cool excellent there we go creating the utility function to read the file system next we'll create a utility function for parsing data from the file system with this utility function we'd like to one Parts each markdown file and get the title date and file name which will be used as ID for the Post URL we saw that in our first video when we started going through and clicking and noticing the URL here the ssg-ssr is there and here we've got the URL here of pre-rendering and two we list the data on the index page sorted by date so create another top level directory called lib Library then inside Library create a full uh file called posts.js and copy and paste this code this is a bunch so let's let's copy and paste this code and then let's try to go through it and see if we you don't need to understand what the code above is doing in order to learn xjs I would love to know this is the point of documentation Nation so we've got import FS from FS for reading and managing files so we've got import path from path and import matter from Gray matter so here we're decluttering a variable const posts directory equals path.join and we've got process.cwd current working directory and we're going to the posts directory which is this one right that we just added our markdown files to not Pages posts so we'll collapse pages so we don't get confused and we're exporting a function get sorted post data so we have some comments here which is nice to help us out get file names under slash posts so another variable we declare of file names which is s dot read directory sync of post directory which is just a path that we declared before reads the contents of the directory is what this dot read directory sync is doing and then all post data we're declaring equals file names.map so we're going we're mapping through each of the files in the directory that we just read with this up here for each file name removing the dot MD from the file name to get the ID so all this is doing this is just saying now declare a variable id const id is for each file name just replace the dot MD at the end with nothing so then you are just left with you know if we're looking at our posts right and the ID would just be SSG Dash SSR stored in this ID variable read markdown file as a string so declaring a full path goes path.join hosts directory which was our original directory that we created and then file name we're still in this mapping function right so we're getting an ID we're getting the path right which is just going to be your you know whatever slash posts slash pre-rendering dot MD right this isn't this isn't the one with other dot MD on there this is the full entire thing and then we use that full path that we just got fs.read file saying synchronously reads the entire contents of a file so then all of that data let's say in ssg-ssr goes into full Contents I don't know what utf-8 is what is utf-8 encoding okay and then we have another variable we declare use gray matter to parse so then so now we have our entire contents of that file and we pass them over to gray matter with the function matter and put our file contents in there and this effectively turns that data into the object that we saw before right on this this example turning our data into turning this into this right and I'd get stored in meta results and then we return finally from our map an object where we put the ID up front that we stored originally and matter results dot data which is this part of the looks great so not even the entire content just the data that we saw between these these lines here that's what we return into all post data right which is itself going to be an array and mapping returns an array so if we look at the map method on mdn we confirm right we create a new array with all that data so this creates an array right returns an array so our all post data which was our big map function that we get here as we return each of these objects we create an array with the object in it with the ID and then the results it's spreading the result.data let's press this object into that object right so now we just have a title of whatever and this we're not going to slug but whatever what is what is our thing title and date and date you know 11 slash one slash whatever it is that would be the first one and then we get another comma another object within an array for however many posts we have in this case we have posts two so this is a second ID second title of whatever two and then the date of you know whatever I don't care I'm going to wrap this so we can see this a little bit better we get the point of what we're looking at here right and now that we have an array we can use the array method sort on this thing and this is just giving us an ascending I guess I guess you would say a date oldest or newest to oldest all right let's go look at sort of a DOT date we're looking at sort if a DOT date is less than b dot date return one otherwise return negative one so if we return a value that is greater than zero and sort a after B right if it's less than zero sort a before B so okay we uh we were instructed that it wasn't important to know what the hell was happening here but I think it's important that we know what's happening here otherwise all this is just nonsense and uh we should take the time to review and get it right so in fact what do we see here we have a large function here that's mapping through all of our data and basically extracting the ID from the file name and parsing the file with matter into a an array of objects and then we sort that array in date order for whatever our needs are here to display them in the order we want them to appear cool excellent always let's see I didn't look at any of this as we were going through that FS is a node module that lets you read files from the file system cool path is a node.js model let's even have like the file paths great if you're not familiar with any of these or if it's been a while for you like it was for me and using these here you go and also we kind of just used our context clues there right matter is a library that we just looked at don't need to read that and it's so tempting sometimes told to just skip over this code but this is the reason for doing documentation Nation for me was to slow down and get better at reading stuff like this so now that blog data is parsed we need to add it to our index page Pages slash index.js we can do this with next.js data fetching method called get static props which we were reading about previously in the next section we'll learn how to implement get static props so parse markdown files here is there uh image display of the array of objects that we just went through the code and understood that we are returning has an array of post data into the page component as props show the list of blog posts on the index page which is this right here right so we're going to end up displaying that array in some way Implement and get static props pre-rendering in next JS next.js has two forms of pre-rendering static generation and server side rendering I think we get it the difference is in when it generates the HTML per page static generation is the pre-rendering method okay cool I understand static generation build time server side each request serversides like old school right importantly next.js lets you choose which pre-rendering form to use on each page you can create a Hybrid next JS app using static narration for most pages and using server-side rendering for others using static generation now we need to add an import for the get sorted post data and call it inside get static props in the pages slash index.js so I'm assuming when they say Pages index.js they mean pages hosts index.j address but they had us do last time so maybe I'm wrong but now we need to add an import for get sorted props get sorted posts data and call it inside get static props open pages index.js in your editor and add the following code above the exported home component so here is our home component we want to add this code up here right so we're going to import get sorted post data there we go from our library slash posts and then we're also going to export an async function called get static crops right where we'll declare a variable all posts data equals the get sorted posts data we just brought in and that is a function so we're gonna we're going to invoke that function and then within this we return an object which has a key of props and the value of props is an object of the all hosts data and we declared above so this is this is just like following the the process right this is get static props which is is typing out as a promise here thank you typescript and what we're returning is the object right which has the props um and it's just the way that next.js handles this particular function by returning all post data inside the props object in get static props the blog post will be passed to the home component as a prop now you can access the blog posts like so so hold on let's let's dig into the way this means by returning all post data inside the prompts object which is what we're doing here this is the object blog post will be passed to the home component so now we just take this and it doesn't just happen automatically right we I don't know why they're they're making I think this was just a little bit worded a little bit confusing for me so that says by returning all post data inside the props object and get static props the blog post will be passed to the home component as a prop which is not true until you pass it as a prop right which means like you have to put it here returning this doesn't automatically pass it until you set it up and access it I maybe it's just me I just don't like the wording of that all posts data right that's our that is what we're passing through here right it's in the same file so it's not like I have to pass this through somewhere else but it still needs this in order to access right that that variable there we go now we can now we can access all post data within this right and you know what I haven't done yet which is going to take a billion years to set up have not started our server and I don't know if it's actually going to boot up that quickly for us last time I did this it took forever okay cool I hit a narrow at first because I was missing some punctuation over here so if you do the same make sure you've got your comma semicolon setup and there's our boy Dale Cooper from our previous setup so cool looks like we're all on the right track here so to deploy blog post what's let's let's update the home component and add another section egg with the data below a section with your self introduction don't forget to also change the props from this to this right now they're telling us to do it twice I don't know whatever I guess it's a nice reminder in case we're trying to speed through this thing so we wanna we're being told at another section down here and there's a bunch of stuff here that they want us to put in here I kind of want to just walk through this so we can take a look what's happening right so we've got the section we're going to have class name and we're going to use JavaScript to figure this thing out and a template literal and we've got some detail Styles right from our previous thing heading MD is the one we had from that and which was just a um what was the file here util styles we chose module right I think that's the one here so we've got our utils module CSS refresh our memory here's our CSS file and we're using this particular one which just increases font size and line height and then within that class name we also have fill styles.padding one pixel which was this one that just adds one pixel of padding to the top and we have an H2 in here that we are doing some more class name stuff with heading uh I don't like that this I can't auto complete this stuff but that's okay this is going to say blog and then we have an on order list which has its own utility class from the class uh from the module that we've imported these still styles.list right and now we're actually going to get into our mapping function from all host data map that's the array that we had before and in here we are destructuring we've got ID date and title let me get some extra function and we're just first going to display we have a line I um a list item here which I there we go Emmett thank you class name holding from our utility file again until files dot list item and we have a key this react loves the keys for whenever we're mapping over anything and they're using the ID here and within this list item we're going to display the title that we are mapping through using a break the ID that we have I can type ID using another break and then our date and it looks like everything and if I didn't mistype something we should go back to R here we go we have the title we have the ID and we have the date so remember that we have we go back and we look at our other file that I close silly we looked at that array that we have with each object right that has the ID the title and the date so we know why we're using dot map to go through the array and we see how we disrupt destructure the things within that object right rather than doing something like for each post right then you would have done like post dot title right to access within an object but instead of doing that we are destructuring the individual things within that object so cool awesome I love it I get it you should now see blog data if you access yes we do congratulations we've successfully fetched external data from the file system and pre-rendered the index page with this data cool we have utilized a function to map through data that we have and return an array of objects that are sorted we have imported that function with its return in a variable that we have declared so this all post data is our array of objects and then we using this getstatic props async function return and object with the props key and the value which is an object of all post data and then we continue pre-rendering and data fetching yet static prop details here's some essential information you should know about get static props external API or query database so in the library post.js we've implemented get sorted post data which fetches data from the file system but you can fetch the data from other sources like an external API endpoint and it'll work just fine so here we're just instead of doing just getting data from our library that we have access to immediately this or just using the fetch um command here and getting back that data right next yes polyfill effect so you don't need to import it that's cool also query the database directly import some database and they're going through a query with select and SQL querying so that's interesting to know I guess cytoprops only runs on the server side it will never run on the client side it won't be included in the JS bundle for the browser I mean you can write code such as direct database queries without them being sent to browsers well that's interesting to know that means the browser isn't actually making that all it's the server that's making that call and then sending it with the code over how's that way development versus production development inside your prep runs on every requesting production it runs a build time or this Behavior can be enhanced using a fallback key return buying get static paths this is meant to be run to build time you'll be able to use data that's only available during request time such as query parameters or HTTP headers okay a lot of things to try to remember about this thing but without actually running into the issues I'm not going to remember them it's just going to be a process of using things and experimentation and seeing what I break aesthetic props can only be exported from a page you can't export it from non-page files okay so that means if we didn't have something here that we were rendering again I mean I guess this is kind of like use effect and calling out to my database and just making a regular react application so instead of running use effect which happens at the time component mounts this is just kind of doing a similar thing maybe I'm wrong but that's kind of the way I'm understanding this what if I need to fetch data at request time since static generation happens once at build time it's not suitable for data that updates frequently or changes on every user request cases like this where your data is likely to change you can use server-side rendering let's learn more about server-side rendering in the next section quick review where does get static props run or reside right good job okay here's the last page in this particular section we're almost done with pre-rendering and data fetching and then we'll call this session because we are learning a bunch of information here that we're not going to really remember right this is this is the hard thing about working through documentation and just to try to get a handle on the functionality of this stuff is like man once I need to use it then I'm going to go back in here now that I know it's here now that I'm familiar with this stuff and I'll be able to reread this and be like oh yeah cool I remember how this works and I can implement the process but until I do that man this is going to just be back here somewhere but not not really in my memory easily retainable one time through fetching data and request time if you need to fetch a data at request time instead of add build time you can try server-side rendering yeah that's what we uh we're talking about right xjs such as data boom to use server side rendering you need to export git server side props instead of get static prop so we're doing the same thing it's called like it's server side of props so I guess that just kind of understanding the difference between the two makes sense using get server side prompts there's a starter code for service on props not necessary to blog for our blog except so we won't be implementing it that's okay it's the exact same setup here and we would just return the same exact way we're just replacing this and next day next JS is just going to do its thing that it knows it needs to do it goes good service is called a request time it's parameter context ooh there is something additional contains request specific parameters you should use get service at prompts only if you need to pre-render a page whose data must be fetched at request time time to First byte ttfb will be slower than get static props because the server must compute and result on every request the result cannot be cached by a CDM without extra configuration so this is really just saying like if I refresh this page it's going to call out every single time right in the exact same way that like a use effect just calling out to a server would do the same thing as soon as I render that component it's going to call out it's going to call out it's going to call out if you do not need to pre-render the data you can also use the following strategy called client-side rendering technically generate pre-render parts of the page that do not require external data when the page loads fetch external data from the client using JavaScript and populate the remaining parts so here's a little image of what this is referring to static generation without data plus fetch data on the client side re-render data you can also pre-render without data and then load the data on the client side next.js builds building app for production here we go statically generate parts of the page that do not our data which is load the request time fetch the data and populate okay I don't know I don't I don't love the way some of the stuff is being explained maybe I'm just lacking some knowledge being at the stage of my Learning Journey that I'm in and okay but it's not really giving me what I think I need to have to walk away from this feeling really confident about the differences and the benefits like I generally understand the concepts but I think this is going to take a couple times really going through to fully get everything that's happening here it's approach works all for dashboard Pages for example because a dashboard is a private user-specific page SEO is not relevant and the page doesn't need to be pre-rendered it is frequently updated which requires fast time so like yeah I think a lot of this stuff is mainly like SEO based right like you if your website performs more efficiently you're going to have a higher um ranking in like a Google you know uh SEO stats and things like that so um that's why this stuff is important for us SWR the team behind xjs has created a react hook for data fetching on the stuff you are highly recommended if you're fishing data on the client side and it was caching revalidation Focus tracking Etc I won't cover details here but know that it exists if we ever need it and there's some documentation so cool this one's been for me a rough one it's important data to understand and to be able to utilize but it was very dry content I'm glad we took the time to go through code because part of documentation nation's goal is reading code better getting better at reading code getting better at understanding someone else's code getting better at being able to go through and explain what's happening even if I'm goofing up a little bit here and there you know this is the the level I'm currently at in my journey let's answer our quick review and then we'll call this one when should you use client side rendering when you can pre-render the data head of a user's request when you need to fetch data and request time instead of build time private user-specific Pages where SEO is not relevant um this one yeah so at least I'm getting the questions correct I'm able to retain some of that information but yeah I don't know this one made my brain hurt a little bit I am ready for a break on this documentation next time we come back we go to Dynamic routes and then API route and then we get to deploy and then we learn all this stuff about SEO which will be maybe we do that depending if it's just me reading stuff I don't really want to do that but we'll see but this is the stuff I'm done uh excited for dynamic routes and API routes specifically all right documentation Nation if you can hear it in my voice this one was a little bit draining it's time to call this session thank you for joining me we'll see you again on the next one
Info
Channel: EricWinkDev
Views: 88
Rating: undefined out of 5
Keywords: nextjs, next.js, next js, reactjs, react.js, react js, react, next, tutorial, how-to, how to, pre-render, pre render, data fetch, data-fetch, fetching, learn coding, how to code, framework
Id: L8AWV_JmUig
Channel Id: undefined
Length: 39min 14sec (2354 seconds)
Published: Wed Jan 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.