typescriptintermediate

Template vs Layout for Re-rendering

Use template.tsx instead of layout.tsx when you need fresh state on every navigation.

typescript
// app/dashboard/template.tsx
// Template re-renders on EVERY navigation (unlike layout)
// Good for: animations, useEffect on route change, form resets

'use client';

import { useEffect } from 'react';
import { motion } from 'framer-motion';

export default function DashboardTemplate({
  children,
}: {
  children: React.ReactNode;
}) {
  useEffect(() => {
    // Runs on every page navigation within /dashboard
    console.log('Dashboard page changed');
  }, []);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      {children}
    </motion.div>
  );
}

// Compare with layout.tsx:
// - layout.tsx: Preserved across navigations, state persists
// - template.tsx: New instance on every navigation, state resets

// app/dashboard/layout.tsx (persistent)
export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="flex">
      <nav className="w-64">Sidebar persists</nav>
      <main className="flex-1">{children}</main>
    </div>
  );
}

Use Cases

  • page transitions
  • analytics tracking
  • form resets on navigation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.