šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on 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>

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *