Next.js/React 환경에서 페이지 이동하는 방법들과 각각의 장단점을 정리해줄게:
useRouter
+ router.push()
const router = useRouter();
router.push('/path');
장점:
단점:
useRouter
+ router.replace()
router.replace('/path');
장점:
단점:
Link
컴포넌트<Link href="/path">이동</Link>
장점:
단점:
window.location.href
window.location.href = '/path';
장점:
단점:
window.location.replace()
window.location.replace('/path');
장점:
단점:
window.history.pushState(null, '', '/path');
장점:
단점:
// 프로그래밍적 이동
const router = useRouter();
router.push('/dashboard');
// 사용자 클릭 기반
<Link href="/dashboard">대시보드</Link>
// 로그인 페이지로 돌아가지 않게
router.replace('/dashboard');
// 새 탭
window.open('https://example.com', '_blank');
// 현재 탭
window.location.href = 'https://example.com';
const handleSubmit = async () => {
const success = await submitForm();
if (success) {
router.push('/success');
} else {
router.push('/error');
}
};
router.back(); // 뒤로가기
router.forward(); // 앞으로가기 (브라우저 히스토리에 있을 때만)
<Link href="/heavy-page" prefetch={false}>
무거운 페이지
</Link>
router.push('/same-page?tab=2', undefined, { shallow: true });
대부분의 경우: useRouter
+ router.push()
또는 Link
컴포넌트
로그인/인증 관련: router.replace()
외부 링크: window.location.href
또는 window.open()
전체 페이지 리셋 필요시: window.location.href
Next.js 환경이라면 가능한 한 Next.js 라우터를 사용하는 게 성능과 사용자 경험 측면에서 최적이야.