[Next.js] Routing 실험

Wendy·2022년 1월 6일
2

학습기록

목록 보기
17/20

Routing

https://nextjs.org/docs/routing/introduction
공식 페이지를 공부하면서 생긴 궁금증을 실험해보았다.

1. routing 시스템에 의해 겹치는 주소 테스트

Predefined routes take precedence over dynamic routes, and dynamic routes over catch all routes. Take a look at the following examples:

pages/post/create.js - Will match /post/create
pages/post/[pid].js - Will match /post/1, /post/abc, etc. But not /post/create
pages/post/[...slug].js - Will match /post/1/2, /post/a/b/c, etc. But not /post/create, /post/abc

1) 미리 정의된 route
2) dynamic route
3) catch all route

위 순서대로 적용된다고 해서
겹치는 주소 테스트를 해보고 싶어졌다.
/about 라우팅 우선순위는 어떻게 될까?

결과

***먼저 적용되는 우선순위***
/pages/about.js 
/pages/about/index.js 
/pages/about/[[...slug]].js
/pages/[slug].js
/pages/[...slug].js

***기타***
/pages/about/[[...slug]].js는
/pages/about.js, /pages/about/index.js와 함께있으면 빌드실패

/pages/[[...slug]].js는 /pages/[...slug].js 둘다있으면 빌드실패

2. Link의 prefetch 기능 테스트

Any in the viewport (initially or through scroll) will be prefetched by default for pages using Static Generation. The corresponding data for server-rendered routes is not prefetched.

화면에 들어오는 Link로 연결된 SG페이지들은 prefetch된다고 하니
Link로 연결된 SG페이지 / SSR페이지
a로 연결된 SG페이지 / SSR페이지
이렇게 4가지 케이스에 대해서 prefetch가 되는지 알아보려고 한다.
(테스트 시 npm run dev 말고 build - start 과정으로 진행해야함)

결과

스크롤을 내리면서 Link로 연결된 SG 페이지 두가지만 prefech 되었다.
first-post.json (404) sg-link.json
첫포스트는 404인데도 값이 온다!

3. Shallow Routing 후 뒤로가기 테스트

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.

/주소에서 시작했다가
router.push('/?counter=10', undefined, { shallow: true })
와 같이 동작시키고나서
뒤로가기 버튼을 누르면 어떻게 될까?

1) 뒤로갈때도 data-fetching이 없다
2) 뒤로갈때는 data-fetching이 일어날것이다
3) push함수지만 replace로 작동해서(?) / 이었던 주소가 덮어씌어져 뒤로 못간다

export function getServerSideProps({ params }) {
  const { id } = params;

  return {
    props: {
      id,
      time: dayjs(new Date()).format("HH:mm:sss"),
    },
  };
}

export default function Post({ id, time }) {
  const router = useRouter();
  
  useEffect(() => {
    router.push(`/ssr/${id}/?counter=10`, undefined, { shallow: true });
  }, []);
  ...
}

결과

정답은 2번!

  1. 일단 뒤로가기 가능
  2. 뒤로갈때 SSR이 다시 일어남
    처음진입 했을때의 시간보다
    뒤로가기 버튼을 눌렀을때의 시간이 더 늦은것으로 보아
    뒤로갔을때도 data-fetching 이 일어났음을 알수있다.
    (아래 화면에는 없지만 network에서도 다시 호출한게 찍혔다)

profile
개발 공부중!

1개의 댓글

comment-user-thumbnail
2022년 1월 20일

공부하시는 방식이 배울점이 많네요. 잘 읽었습니다.

답글 달기