1. 8
    Setup the Root Layout in a Next.js App Router Project
    3m 16s

Setup the Root Layout in a Next.js App Router Project

Ben Patton
InstructorBen Patton
Share this video with your friends

Social Share Links

Send Tweet

When we initialized the app router Nextjs automatically created our root level layout.tsx file in the app router.

We will start migrating our pages router app to the app router by adding components from _app.tsx in the pages router to the root layout in our app router.

Instructor: [0:00] You may have noticed that when we initialized the app router in the last lesson that this layout.tsx file was created. If we come in here, we can look at this. We notice we have our metadata and we have this root layout. This root layout replaces our _app.tsx and our _document.tsx files in the pages router.

[0:21] We can have both until we're ready to remove the _app.tsx and the document.tsx files from the pages router, but we want to gradually move things over. First, we want to bring in our navbar and our styles to the root layout.

[0:38] If we come up here, we can import our styles and navbar and then we can just wrap our children in the navbar. We can save this and we'll come back over here and we see that we're getting an error.

[0:56] This is because, currently, and by default, every route and layout is a server component. To change this -- so that we can keep with our client-side app before we are ready to move over to using React Server Components --we need to comment out the metadata because this runs on the server, and we need to add the "use client" directive.

[1:20] Now, if we save this and come back to our app, we see that we are also getting errors for our query client. That's because, in our navbar, we are querying for user data so we need to also bring in that information. We can come into our app.tsx. Let's grab our QueryClientProvider and we can paste it here as well. Let's wrap that and make sure we keep that there.

[1:51] Then, we need to import that as well. We can grab the same information here, copy it, paste it into our layout. We won't need the hydrate component and we'll make sure we import React.

[2:15] Then, we also need to initialize our QueryClient. We can grab this useState here, and paste it in right here. The last thing we want to grab is our ReactQueryDevtools. We can paste them within the QueryClient. Now, if we save and we come back, we see that we are getting our app as expected.

[2:43] In review, we got a simple start with layouts in the app router. We first imported our navbar and styles. We got errors because the navbar is a client component. We had to change our layout to be a client component.

[3:00] The navbar also uses React Query. To use React Query, we had to import our QueryClientProvider and wrap our navbar and children with it so that all subroutes and layouts of the root layout have access to the React Query content.