Mastering NextJS Layout Files

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional NextJS Lessons

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
🚨 Work In Progress 🚧
Subscribe for Launch

Mastering NextJS Layout Files

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Core concept

  • A layout in NextJS is a user interface component that is shared between multiple pages.
  • You can define a layout by default exporting a React component from a code file called layout (with code extension of your preference, ours is .tsx).
  • The component accepts a children prop. Render it wherever you want, and even add additional common components (e.g. nav, footer) if required.

This is demonstrated in the below example,

app/dashboard/layout.tsx
app/dashboard/page.tsx
export default function Layout({ children }: React.PropsWithChildren) {
return (
<div>
{children}
<footer>
© <b>Boolean</b><i>Art</i>
</footer>
</div>
);
}

Layout and sub-routes

When we provide a layout component for a route it is also automatically used for all sub routes.

This is demonstrated in the below example where our dashboard/layout.tsx file is affecting /dashboard as well as /dashboard/subscriptions

app/dashboard/layout.tsx
app/dashboard/page.tsx
app/dashboard/subscriptions/page.tsx
export default function Layout({ children }: React.PropsWithChildren) {
return (
<div>
{children}
<footer>
© <b>Boolean</b><i>Art</i>
</footer>
</div>
);
}

Layouts Preserve State

On client side navigation between routes that have the same layouts, the layout components preserves state, remain interactive, and do not re-render.

This is the main reason for using a layout file instead of just putting the common code into the individual components. Better performance, and more control over the UX 💪

This is demonstrated in the below example where the menu preserves its open/closed status as we navigate to different routes.

lib/DashboardMenu.tsx
app/dashboard/layout.tsx
app/dashboard/page.tsx
app/dashboard/subscriptions/page.tsx
"use client";

import { useState } from "react";
import Link from "next/link";
import styles from "./DashboardMenu.module.css";

export const DashboardMenu = () => {
const [isOpen, setIsOpen] = useState(false);

return (
<nav className={styles.menu}>
<button onClick={() => setIsOpen(!isOpen)}>
Dashboard Menu {isOpen ? "▲" : "▼"}
</button>

{isOpen && (
<ul>
<li>
<Link href="/dashboard">Home 🏠</Link>
</li>
<li>
<Link href="/dashboard/subscriptions">Subscriptions 🚀</Link>
</li>
</ul>
)}
</nav>
);
};

Root Layout

Every NextJS Application actually needs to have a layout file at the root of the app directory and therefore it is called the root layout. This file must render the html and the body tags.

Every NextJS project as one, you can use it to render something you need to use throughout your website e.g a floating action button (aka fab).

app/layout.tsx
import type { Metadata } from "next";
import "./globals.css";

export const metadata: Metadata = {
title: "BooleanArt NextJS App",
description: "Sample App for the BooleanArt NextJS Course",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>
<a href="https://booleanart.com" target="_blank" className="fab">
<img alt="fab" src="/images/fab.png" />
</a>
{children}
</body>
</html>
);
}

Layouts Can Be Nested

You can even provide layout files in the sub routes which will allows you to nest the layout components.

In fact this is how we've been demoing. E.g. for /dashboard the following layout files came into action

  • /layout.tsx
  • /dashboard/layout.tsx

You can create as many nested layout files as your use case requires 🌹

javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

A layout in next JS is a user interface component that is shared between multiple pages. You can define a layout by default, exporting a React component from a code file called layout. For example, within the app directory, we create a page component as well as a layout component. And now when a request comes in for slash, which would normally only be served by the page, next case we'll render out the layout component and passing the rendered page component as the children prop to the layout. Let's demonstrate this By creating a new page under the dashboard route, we render out a simple heading, and if you were to visit the page right now,

00:34

that is all what we would see. Now let's create a new layout file under the dashboard folder. The next year's contract for a layout file is that it must export a default component, and this component must accept children as props. We can use the past in children to place them in a specific place and even add additional components. For example, here we are adding a simple footer, so now if you visit the dashboard route, we can see this layout component that displays the footer along with the children, replaced by the dashboard page contents. When we provide a layout component for a route, it is also automatically used for all sub routes. We know that if the layout on the page are next

01:09

to each other next year renders out the layout and passes in the page. But in addition to this, for all of the sub routes, for example, a subro under the courses folder, next case will actually render that page within the same layout. What's more is that as we navigate between slash and slash courses, the layout will stay mounted and the only thing that will change will be the past in children prop. Let's demonstrate this with the code example. We've already seen that the dashboard layout is displaying the page that is next to it. Let's create a sub route called subscriptions by creating a page under that folder, just like the root dashboard page renders out a simple

01:42

heading, the dashboard subscriptions page will also render a simple H one. On the dashboard route. We can see the page rendered heading along with the footer. And similarly, if you go to dashboard slash subscriptions, we see the H one rendered by that specific page along with the footer that is rendered by the layout, which is coming into play for both of these routes. On client side, navigation between routes that have the same layouts, the layout components preserve state, remain interactive and do not render. To demonstrate why this is important, we will create a component that maintains some local client side state. The component we are creating is a dropdown menu

02:15

for the dashboard that preserves the state, whether it is open or not. We create a simple button, which allows the user to toggle the state between open and closed, and then when it is open, we will render out a list containing the links to different routes within the dashboard. If next days didn't have the feature of layout pages, you would think that you could just add the menu manually to the different pages within the dashboard, but you would be missing out on a key feature offered by layouts. React is actually not able to reconcile the same component between different pages, so even though the different pages are rendering the same component every single time we go

02:48

to a different page, the component is completely blown away and rendered from scratch, which is why we lose the state, for example, whether it is open or closed. To fix this and make our code Simpler, we remove the common component from the individual routes and instead render it within the layout component. With these modifications in place, let's take a look at the application within the browser. Within the ui, as we navigate the different routes, you can see that the state of the menu, whether it's open or closed, is preserved and it's within our control whether we want the menu to be open or not. Every next year's application actually needs

03:21

to have a layout file at the root of the appy, and it is therefore called the root layout. Since it is required no surprise within our sample codes, we've always had this file. Next year's has a special requirement specific to the root layout file. It must render an HTMO and a body tag. Beyond that, you are free to do what you want. For example, you can place some common user interface over here that will be displayed throughout your application. Here we are rendering a fab or a floating action button, which links to our website With this code in place, if you visit any route within our application, it'll still cascade over to the root layout,

03:54

which is why we will always see this button. You can even provide layout files in sub routes, which allows you to nest the layout components. Consider the case where we have a layout in the route and then we have a courses sub route page. If we create another layout under the courses folder, when a request comes in for slash courses next year, we'll render the route layout and then pass in the rendered child layout as the children prop, and for that child layout, it'll pass in the courses page and we don't actually need to build a new demo in order to demonstrate this concept as it is already happening within an application.

04:26

When the user visits slash dashboard, the page component is passed as children to the dashboard layout component, which is then in turn passed as children to the root layout component, which is why in the final result shown by the browser, we can see the page as well as the dashboard layout that adds the menu as well as the root layout that adds the fab. We are only using two layout components over here, but you can ask as many layout components as you need for your desired use case.

Professional NextJS

Professional NextJS

1.Course Intro
free
⏱️ 2:05
2.Get Setup
free
⏱️ 2:05
3.Project Template
free
⏱️ 5:45
4.Introducing FullStack React
free
⏱️ 4:57
5.App Router Reference
free
⏱️ 7:08
6.NextJS Server vs. "use client" Rendering
⏱️ 5:01
7.Nesting Server and Client Components
⏱️ 8:51
8.Client Only Components
⏱️ 3:48
9.Global CSS in NextJS
⏱️ 6:30
10.CSS Modules and SASS
⏱️ 4:15
11.Tailwind CSS
⏱️ 5:17
12.NextJS Custom Fonts
⏱️ 4:08
13.Static vs Dynamic Rendering
⏱️ 4:55
14.NextJS Link Component
⏱️ 3:20
15.NextJS Link Prefetching
⏱️ 5:49
16.Navigation Scroll with Link
⏱️ 2:02
17.Replace Navigation History
⏱️ 1:35
18.NextJS Image Component
⏱️ 7:01
19.Dynamic Image URLs
⏱️ 5:34
20.Safe Colocation with Private Folders
⏱️ 2:12
21.NextJS Route Groups
⏱️ 3:07
22.Dynamic Routes
⏱️ 5:37
23.NextJS API Routes
⏱️ 6:03
24.NextRequest and NextResponse
⏱️ 2:41
25.Cookies in API Handlers
⏱️ 4:25
26.React Suspense Simplified
⏱️ 2:23
27.Power of Suspense Boundaries
⏱️ 3:52
28.use Promises
⏱️ 3:24
29.Stream Promise Results from Server to Client
⏱️ 3:03
30.use Requires a Cached Promise
free
⏱️ 2:30
31.Suspense Error Boundaries
⏱️ 4:42
32.React Server Functions
⏱️ 4:50
33.Server Actions for Powerful Forms
⏱️ 5:35
34.useActionState to Simplify Form Actions
⏱️ 6:38
35.React Serializable Types
⏱️ 2:42
36.Create Dynamic Images with NextJS ImageResponse
⏱️ 5:54
37.Deploy NextJS Application to Production
⏱️ 3:51
38.NextJS Environment Variables Masterclass
⏱️ 3:50
39.Deploying and Managing Environment Variables
⏱️ 4:38
40.Using Databases for Dynamic Server Side State
free
⏱️ 7:34
41.Mastering NextJS Layout Files
⏱️ 4:54
42.Client State Management with NextJS
⏱️ 3:48
43.Client State Management In Action
⏱️ 8:04
44.Using Client State Management Libraries
⏱️ 5:25
45.Detecting Server vs Client Runtime and useEffect
⏱️ 4:33
46.Demystifying ISR vs SSR vs SSG
⏱️ 3:07
47.Static Site Generation or SSG with NextJS
⏱️ 3:16
48.Incremental Static Regeneration (ISR) Simplified
⏱️ 2:51
🚨 Work In Progress 🚧
Subscribe for Launch