C.W.K.
Stream
Lesson 10 of 10 · published

Navigation

~20 min · Link, useRouter, redirect, prefetch

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Link component 가 href 보다 더 함

가 client-side transition 처리, 목적 route prefetch, layout state 보존. In-app navigation 어디든 써. 평범한 는 full reload trigger.

Programmatic navigation

Client Component 안에서 next/navigationuseRouter() 가 코드로 navigate 할 수 있게. Server Component 는 redirect() 가능.

실제 쓰는 hook

Hook반환위치
useRouter()Router method (push, replace, refresh)Client
usePathname()현재 pathname stringClient
useSearchParams()URLSearchParamsClient
useSelectedLayoutSegment()현재 layout 의 active child segmentClient

Code

Link + prefetch·tsx
import Link from 'next/link';

export function Nav() {
  return (
    <nav className="flex gap-3">
      <Link href="/">Home</Link>
      <Link href="/about">About</Link>
      <Link href="/blog/hello-world">Blog</Link>
      <Link href="/dashboard" prefetch={false}>
        Dashboard (no prefetch)
      </Link>
    </nav>
  );
}
Form 에서 programmatic push·tsx
'use client';
import { useRouter } from 'next/navigation';
import { useTransition } from 'react';

export function LoginForm() {
  const router = useRouter();
  const [pending, start] = useTransition();

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        start(async () => {
          const ok = await login();
          if (ok) router.push('/dashboard');
        });
      }}
    >
      <button disabled={pending}>{pending ? 'Signing in&hellip;' : 'Sign in'}</button>
    </form>
  );
}
Server-side redirect, client JS 0·tsx
import { redirect } from 'next/navigation';

export default async function Page() {
  const session = await getSession();
  if (!session) redirect('/login');
  return <Dashboard session={session} />;
}

External links

Exercise

App 안 모든 <a href=…><Link> 로 교체. Auth 필요 route 에 server-side redirect 추가, form 성공 후 client-side router.push 박아.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.