usePathname
usePathname
은 현재 URL의 경로명을 읽을 수 있게 해주는 클라이언트 컴포넌트 훅입니다.
app/example-client-component.tsx
"use client";
import { usePathname } from "next/navigation";
export default function ExampleClientComponent() {
const pathname = usePathname();
return <p>Current pathname: {pathname}</p>;
}
app/example-client-component.js
"use client";
import { usePathname } from "next/navigation";
export default function ExampleClientComponent() {
const pathname = usePathname();
return <p>Current pathname: {pathname}</p>;
}
usePathname
은 의도적으로 클라이언트 컴포넌트 사용을 요구합니다. 클라이언트 컴포넌트가 성능을 저해하는 요소가 아니라는 점을 주목해야 합니다. 이들은 서버 컴포넌트 아키텍처의 필수적인 부분입니다.
예를 들어, usePathname
을 사용하는 클라이언트 컴포넌트는 초기 페이지 로드 시 HTML로 렌더링됩니다. 새 라우트로 이동할 때 이 컴포넌트를 다시 가져올 필요가 없습니다. 대신, 컴포넌트는 한 번 다운로드되고(클라이언트 JavaScript 번들에서) 현재 상태에 따라 다시 렌더링됩니다.
알아두면 좋은 점:
- 서버 컴포넌트에서 현재 URL을 읽는 것은 지원되지 않습니다. 이는 페이지 탐색 간에 레이아웃 상태를 보존하기 위한 의도적인 설계입니다.
- 호환성 모드:
- 폴백 라우트가 렌더링되고 있거나
pages
디렉토리 페이지가 Next.js에 의해 자동으로 정적 최적화되었고 라우터가 준비되지 않은 경우usePathname
은null
을 반환할 수 있습니다.- Next.js는 프로젝트에
app
과pages
디렉토리가 모두 있는 것을 감지하면 자동으로 타입을 업데이트합니다.
매개변수
const pathname = usePathname();
usePathname
은 어떤 매개변수도 받지 않습니다.
반환값
usePathname
은 현재 URL의 경로명을 나타내는 문자열을 반환합니다. 예를 들어:
URL | 반환값 |
---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
예시
라우트 변경에 대응하여 작업 수행하기
app/example-client-component.tsx
"use client";
import { usePathname, useSearchParams } from "next/navigation";
function ExampleClientComponent() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
// 여기에서 무언가를 수행...
}, [pathname, searchParams]);
}
app/example-client-component.js
"use client";
import { usePathname, useSearchParams } from "next/navigation";
function ExampleClientComponent() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
// 여기에서 무언가를 수행...
}, [pathname, searchParams]);
}
버전 | 변경사항 |
---|---|
v13.0.0 | usePathname 도입됨. |