DEV Community

Cover image for Templates in Next.js
Khan Rabiul
Khan Rabiul

Posted on

Templates in Next.js

In Next.js layout.tsx is a shared UI component between routes. layout.tsx never rerenders when we navigate from one route to another. We use layout to render static elements that are not supposed to be changed. Like, the Header, Footer, etc. It means, layout keeps your component/pages or UI the same way and renders the page.tsx in it as children, if you want.

layout example

Difference between layout and template

Just like layout template also wraps the pages and components as children. But the main difference between layout and template is, layout can keep the current state, but template can't. That's why layout does not change the UI or does not manipulate the DOM. On the other hand, template does not hold the state value. It changes the state rerenders the UI, and manipulates the DOM.

Creating a template is very simple.

  • Create a file named template.tsx/jsx/js.. in your desired directory.
  • In the template, returning a React component is compulsory.
  • Do as you do in layout.tsx
import SignUp from './signup';

export default function MyTemplate({ children }: { children: React.ReactNode }) {
  return (
    <main>
      <SignUp />
      {children}
    </main>
  );
}

Enter fullscreen mode Exit fullscreen mode

In summary, don't use template for static assets. Use it for where state needs to be changed and rerender the component.


'use client'

Sometimes you may need to use 'use client'.

  • When you use any React hook or state (useState, useEffect) in your template
  • Attaches event handlers or relies on browser APIs (window, document)
  • Imports other Client Components (e.g., a carousel, chart, or provider)
  • Once "use client" is present, all imports become part of the client bundle.

Top comments (0)