#What is the use case of templates?

1 messages · Page 1 of 1 (latest)

shrewd lark
#

I know it renders on every navigation, unlike layouts. But I'm not sure where to use it.

steep lodgeBOT
#

Hi @shrewd lark. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Templates in Next.js are similar to layouts in that they wrap each child layout or page. However, unlike layouts that persist across routes and maintain state, templates create a new instance for each of their children on navigation. This means that when a user navigates between routes that share a template, a new instance of the component is mounted, DOM elements are recreated, state is not preserved, and effects are re-synchronized.

You might choose a template over a layout if you want:

  • Features that rely on useEffect (e.g logging page views) and useState (e.g a per-page feedback form).
  • To change the default framework behavior. For example, Suspense Boundaries inside layouts only show the fallback the first time the Layout is loaded and not when switching pages. For templates, the fallback is shown on each navigation.

A template can be defined by exporting a default React component from a template.js file. The component should accept a children prop. Here's an example:

export default function Template({ children }: { children: React.ReactNode }) {
 return <div>{children}</div>
}

In terms of nesting, template.js is rendered between a layout and its children.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: