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.
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 aReact componentis 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>
);
}
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
Reacthookorstate(useState, useEffect) in yourtemplate - Attaches
event handlersor relies on browserAPIs(window,document) - Imports other Client Components (e.g., a
carousel,chart, orprovider) - Once
"use client"is present, all imports become part of the client bundle.

Top comments (0)