[17] Shallow Routing

적자생존·2022년 4월 9일
0

router

목록 보기
3/3

1. shallow routing이란

shallow routingdata fetching 메서드(getServerSideProps, getStaticProps, getInitialProps)를 다시 사용하지 않고 URL을 변경하는 방식이다.
state를 잃지 않으면서 pathnamerouter객체(useRouter, sithRouter가 추가된)를 통한 query를 업데이트 할 수 있음.
shallow routing을 위해서는 shallow 옵션을 true를 바꿔 줘야함.
불필요한 서버 연산을 최소화 하고 필요한 상태 값을 라우터에 넣어서 전달하는 것

2. data fetching 메서드

Next.js에서는 data fetching 메서드를 제공함. 사이트를 렌더링하기 전 어떤 데이터를 이용해서 페이지를 생성할 것인지에 대한 함수를 작성하는 기능을 말함

가.getStaticProps

getStaticProps는 데이터를 패치하는 함수임. Next.js에 getStaticProps가 있다면 페이지 생성시 자동으로 실행되며 그 props를 컴포넌트에 전송함

나. getStaticPaths

getStaticPaths은 Next.js에서 동적라우팅이 가능하게끔 만들어 주는 data fetching 메서드임. 즉 페이지 별로 라우팅을 주지 않아도 []을 이용해 동적라우팅이 일어나게 해주는 메서드임

다. getServerSideProps

getServerSidePropsgetStaticProps과 비슷하지만 서버 사이드 렌더링을 위한 함수임. getStaticProps처럼 컴포넌트에 props를 넘겨준다는 공통점이 있으나 빌드 시가 아닌 매 request마다 실행된다는 차이점이 있음

3. shallow routing 적용

import { useEffect } from 'react'
import { useRouter } from 'next/router'

// Current URL is '/'
function Page() {
  const router = useRouter()

  useEffect(() => {
    // Always do navigations after the first render
    router.push('/?counter=10', undefined, { shallow: true });
    // OR
    // router.push(
    //   {
    //     pathname: "/users",
    //     query: { ...values, page: 1 }
    //   },
    //   undefined,
    //   { shallow: true }
    // );
  }, [])

  useEffect(() => {
    // The counter changed!
  }, [router.query.counter])
}

export default Page

최초 렌더링 이후 라우터는 /?counter=10으로 업데이트 됨
위의 코드를 실행하면

import { useRouter } from 'next/router'
import Link from 'next/link'
import { format } from 'url'

let counter = 0

export async function getServerSideProps() {
  counter++
  return { props: { initialPropsCounter: counter } }
}

export default function Index({ initialPropsCounter }) {
  const router = useRouter()
  const { pathname, query } = router

  const reload = () => {
    router.push(format({ pathname, query }))
  }
  const incrementCounter = () => {
    const currentCounter = query.counter ? parseInt(query.counter) : 0
    const href = `/?counter=${currentCounter + 1}`

    router.push(href, href, { shallow: true })
  }

  return (
    <div>
      <h2>This is the Home Page</h2>
      <Link href="/about">
        <a>About</a>
      </Link>
      <button onClick={reload}>Reload</button>
      <button onClick={incrementCounter}>Change State Counter</button>
      <p>"getServerSideProps" ran for "{initialPropsCounter}" times.</p>
      <p>Counter: "{query.counter || 0}".</p>
    </div>
  )
}

가 되며 reload하면 counter가 늘어나지만 props를 타지 않기 때문에 서버의 리소스를 아낄 수 있음.
출처 : https://github.com/Road-of-CODEr/we-hate-js/blob/master/Front-End/Next.js/routing/shallowRouting.md

profile
적는 자만이 생존한다.

0개의 댓글