ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Link , Router 비교
    FrontEnd/Next.js 2023. 11. 16. 16:03
    • 페이지 이동시 <a> 태그를 사용하는 것은 SPA 페이지인 Next.js 에서 효율적이지 못함. 
    • a 태그로 이동 시 새로고침을 하기 때문에 그 과정에서 빈 화면이 보일 수도 있고 통신을 새롭게 하다 보니 성능 및 사용자 경험 측면에서 떨어질 수 밖에 없다.
    • 새로고침 없이 페이지 이동을 위한 (SPA에 위배되지 않기 위해) 라우팅 방식에는 <Link> 와 Router 가 있음

    1.  Link 

    • Link 태그에는 href 속성을 추가하여 가고자 하는 주소(페이지)를 넣는다 
    • 새로고침 없이 페이지 전환이 됨.
    • Client-side navigation 방식으로 ,  JS로 페이지 전환이 이뤄짐
    • <Link> is a React component that extends the HTML <a> element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.
    • 모든 경우는 아니지만 a 태그를 생성하기 때문에 Router 보다 SEO에 유리함
    import Link from 'next/link'
     
    function Home() {
      return (
        <ul>
          <li>
            <Link href="/">Home</Link>
          </li>
          <li>
            <Link href="/about">About Us</Link>
          </li>
          <li>
            <Link href="/blog/hello-world">Blog Post</Link>
          </li>
        </ul>
      )
    }
     
    export default Home

    2. Router

    • window.history.pushState 와 유사함
    • next 13 버전부터 page 라우터보다 app라우터를 지향하기 시작하면서 router는 Next/navigation 사용을 권고함(The useRouter from next/router is to be used in the pages folder, the initial way of setting up routes in Next.js. Since v13, they introduced a new directory called app, built on top of Server Components, where you define routes differently and use useRouter from next/navigation:)
    • 크롤러가 링크를 감지하지 못하여 SEO에 좋지 않을 수 있음
    • 대부분 onClick과 같은 이벤트 핸들러와 같이 사용 함.
    • 주요 옵션
      • router.push
        페이지가 이동되며 히스토리 스택이 쌓인다.
        Main -> Login -> List에서 마이페이지로 push 하면 Main -> Login -> List -> Mypage
      • router.replace
        페이지가 이동되며 히스토리 스택이 교체된다.
        Main -> Login -> List 에서 마이페이지로 replace 하면 Main -> Login -> Mypage💡
      • router.back
        뒤로 가기 기능이며, "window.history.back()"과 동일하다.
      • router.reload
        새로고침 기능이며, "window.location.reload()"와 동일하다.
    'use client'
     
    import { useRouter } from 'next/navigation'
     
    export default function Page() {
      const router = useRouter()
     
      return (
        <button type="button" onClick={() => router.push('/dashboard')}>
          Dashboard
        </button>
      )
    }
Designed by Tistory.