Server-side data fetching in Next.js 12 vs. 13

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's talk about data fetching in next 12 versus next 13. I've got a next 12 app here with two routes home and about and we want to add some data to our shared header component so uh we're here at the home page but our header component is being rendered in underscore app so to get some Dynamic data to a app we need to come over to our index page and we can fetch data using get server side props this is an async function which we'll use to await this call to get user which gives us a user we can return in props and so now back in our app file if we go ahead and log the page props and pop open the console we'll see our user is now available and we have a name property here so let's go ahead and pass name pageprops.user.name to our header open our header we'll expose that prop and now we can come down right here in our header and paste in a little welcome message so we now have got some Dynamic data being passed to our shared header but if we visit the about page we're going to see an error and that's because our about page is not currently fetching data so let's go ahead and copy over our data fetching code from index to about we'll import get user save and uh now if we refresh we're going to see about works just fine so both of these pages are rendering but it's kind of a bummer that we have to copy this over to every new page we make we've introduced some implicit coupling between each new page we create and our shared header component in our underscore app file so let's see how this looks in next 13. I've got the same app here in next 13 we want to add the message to the header so let's come and find it this is being rendered right in our root layout right here so we can pop this open and in next 13 we can fetch data directly inside of components so let's go ahead and turn this into an async function we'll grab the user from await get user and now if we log the user hit save and come over and refresh well we're not going to see it over here in the browser but if I pop open the terminal we're actually going to see it rendering right here and that's because this component is a server component so uh now we can go ahead and destructure the name and drop in our new element right here and check this out home page about page and the header is fetching its data and rendering it just fine without any changes to either one of our Pages thanks to the power of nested layouts and server components
Info
Channel: Vercel
Views: 66,040
Rating: undefined out of 5
Keywords: server side rendering, next js 13, next js, server side rendering explained, next js tutorial
Id: i8PsGvDas-s
Channel Id: undefined
Length: 2min 56sec (176 seconds)
Published: Fri Jan 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.