Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Templates vs Layouts in NextJs

Exploring the differences and similarities between templates and layouts in NextJs.

Alongside the layout.js files, we have seen that another reserved filename in NextJs is the template.js.

So, what are the differences and similarities between the layout and the template files?

Similarities between templates and layouts

Both the templates and layouts serve very similar purposes in NextJs. They wrap the content of the page with the needed content decorations. Therefore both are perfect places for common parts such as an app navigation or a footer.

The template.js and layout.js files need to accept a children prop which will indicate the placeholder for the actual page content. Their basic definitions are very similar:

// app/layout.js
export default function MainLayout({ children }) {
    return (
        <div style={{"border":"10px solid blue"}}>
            {children}
        </div>
  )
}
// app/template.js
export default function MainTemplate({ children }) {
  return <div {{"border":"10px solid red"}}>
    {children}
   </div>
}

Differences between templates and layouts

The main difference between a template and a layout comes from how they manage the state: layouts preserve the state when the user navigates from one page to another while templates are not doing that.

Templates are fully remounted between page navigation while the layouts only mount the part representing the content of the newly loaded page but keep all the common elements untouched.

When to use templates and when to use layouts in NextJs

Given that layouts don't remount shared components they come with considerable performance improvements. Also layouts make state management easier.

Therefore, we should use layouts as the default option.

However, there are cases when using NextJs templates is a better fit. Some examples:

Can I use templates and layouts at the same time?

Yep, we can have a template.js and a layout.js file in the same folder.
So let's say we have the following:

/app
    layout.js
    page.js
    template.js

Then, according to the offical documentation, the final output will be:

<Layout>
  {/* Note that the template is given a unique key. */}
  <Template key={routeParam}>{children}</Template>
</Layout>
Home Screencasts Best of Newsletter Search X