# nav-link-component: Prefer Link Component for Navigation ## Priority: MEDIUM ## Explanation Use the `` component for navigation instead of `useNavigate()` when possible. Links render proper `` tags with valid `href` attributes, enabling right-click → open in new tab, better SEO, and accessibility. ## Bad Example ```tsx // Using onClick with navigate - loses standard link behavior function PostCard({ post }: { post: Post }) { const navigate = useNavigate() return (
navigate({ to: '/posts/$postId', params: { postId: post.id } })} className="post-card" >

{post.title}

{post.excerpt}

) } // Problems: // - No right-click → open in new tab // - No cmd/ctrl+click for new tab // - Not announced as link to screen readers // - No valid href for SEO ``` ## Good Example ```tsx import { Link } from '@tanstack/react-router' function PostCard({ post }: { post: Post }) { return (

{post.title}

{post.excerpt}

) } // Benefits: // - Renders
// - Right-click menu works // - Cmd/Ctrl+click opens new tab // - Screen readers announce as link // - Preloading works on hover ``` ## Good Example: With Search Params ```tsx function FilteredLink() { return ( View Electronics ) } // Preserving existing search params function SortLink({ sort }: { sort: 'asc' | 'desc' }) { return ( ({ ...prev, sort })} > Sort {sort === 'asc' ? 'Ascending' : 'Descending'} ) } ``` ## Good Example: With Active States ```tsx function NavLink({ to, children }: { to: string; children: React.ReactNode }) { return ( {children} ) } // Or use render props for more control function CustomNavLink({ to, children }: { to: string; children: React.ReactNode }) { return ( {({ isActive }) => ( {children} {isActive && } )} ) } ``` ## Good Example: With Preloading ```tsx function PostList({ posts }: { posts: Post[] }) { return ( ) } ``` ## When to Use useNavigate Instead ```tsx // 1. After form submission const createPost = useMutation({ mutationFn: submitPost, onSuccess: (data) => { navigate({ to: '/posts/$postId', params: { postId: data.id } }) }, }) // 2. After authentication async function handleLogin(credentials: Credentials) { await login(credentials) navigate({ to: '/dashboard' }) } // 3. Programmatic redirects useEffect(() => { if (!isAuthenticated) { navigate({ to: '/login', search: { redirect: location.pathname } }) } }, [isAuthenticated]) ``` ## Context - `` renders actual `` tags with proper `href` - Supports all standard link behaviors (middle-click, cmd+click, etc.) - Enables preloading on hover/focus - Better for SEO - crawlers can follow links - Reserve `useNavigate` for side effects and programmatic navigation - Use `` component for immediate redirects on render