|
|
|
|
|
title: template.js |
|
|
description: API Reference for the template.js file. |
|
|
|
|
|
|
|
|
A **template** file is similar to a [layout](/docs/app/getting-started/layouts-and-pages |
|
|
|
|
|
They are useful when you need to: |
|
|
|
|
|
- Resynchronize `useEffect` on navigation. |
|
|
- Reset the state of a child Client Components on navigation. For example, an input field. |
|
|
- To change default framework behavior. For example, Suspense boundaries inside layouts only show a fallback on first load, while templates show it on every navigation. |
|
|
|
|
|
|
|
|
|
|
|
A template can be defined by exporting a default React component from a `template.js` file. The component should accept a `children` prop. |
|
|
|
|
|
<Image |
|
|
alt="template.js special file" |
|
|
srcLight="/docs/light/template-special-file.png" |
|
|
srcDark="/docs/dark/template-special-file.png" |
|
|
width="1600" |
|
|
height="444" |
|
|
/> |
|
|
|
|
|
```tsx filename="app/template.tsx" switcher |
|
|
export default function Template({ children }: { children: React.ReactNode }) { |
|
|
return <div>{children}</div> |
|
|
} |
|
|
``` |
|
|
|
|
|
```jsx filename="app/template.js" switcher |
|
|
export default function Template({ children }) { |
|
|
return <div>{children}</div> |
|
|
} |
|
|
``` |
|
|
|
|
|
In terms of nesting, `template.js` is rendered between a layout and its children. Here's a simplified output: |
|
|
|
|
|
```jsx filename="Output" |
|
|
<Layout> |
|
|
{/* Note that the template is given a unique key. */} |
|
|
<Template key={routeParam}>{children}</Template> |
|
|
</Layout> |
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Template accepts a `children` prop. |
|
|
|
|
|
```jsx filename="Output" |
|
|
<Layout> |
|
|
{/* Note that the template is automatically given a unique key. */} |
|
|
<Template key={routeParam}>{children}</Template> |
|
|
</Layout> |
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
- **Server Components**: By default, templates are Server Components. |
|
|
- **Remount on navigation**: Templates receive a unique key automatically. Navigating to a new route causes the template and its children to remount. |
|
|
- **State reset**: Any Client Component inside the template will reset its state on navigation. |
|
|
- **Effect re-run**: Effects like `useEffect` will re-synchronize as the component remounts. |
|
|
- **DOM reset**: DOM elements inside the template are fully recreated. |
|
|
|
|
|
|
|
|
|
|
|
| Version | Changes | |
|
|
| |
|
|
| `v13.0.0` | `template` introduced. | |
|
|
|