본문 바로가기
STUDY

노마드 코더 NEXT JS 강의 정리 2

by 3급우사기 2024. 3. 7.

https://nomadcoders.co/nextjs-for-beginners

 

NextJS 14 시작하기 – 노마드 코더 Nomad Coders

NextJS 14 For Beginners

nomadcoders.co

자 남은 부분 정리 들어갑니다.

Next js 정리갑니다잉

#3 DATA FETCHING

 

Fetch
Next.js는 서버의 각 요청이 자체 영구 캐싱 시맨틱을 설정할 수 있도록 기본 Web fetch() API를 확장.
서버 컴포넌트 내에서 직접 비동기 및 대기 상태로 fetch를 호출할 수 있다.

 

Loading UI and Streaming
특수 파일 loading.js를 사용하 React Suspense로 로딩 UI를 만들 수 있다.

이 규칙을 사용하면 경로 세그먼트의 콘텐츠가 로드되는 동안 서버에서 즉각적인 로딩 상태를 표시할 수 있다.

렌더링이 완료되면 새 콘텐츠가 자동으로 교체

 

loading.js 외에도 자체 UI 컴포넌트에 대한 Suspense 바운더리를 수동으로 생성할 수도 있다.

앱 라우터는 Node.js 및 Edge 런타임 모두에 대해 Suspense를 사용한 스트리밍을 지원.

import { Suspense } from 'react'
import { PostFeed, Weather } from './Components'
 
export default function Posts() {
  return (
    <section>
      <Suspense fallback={<p>Loading feed...</p>}>
        <PostFeed />
      </Suspense>
      <Suspense fallback={<p>Loading weather...</p>}>
        <Weather />
      </Suspense>
    </section>
  )
}

 

Promise.all()

Promise.all() 메서드는 순회 가능한 객체에 주어진 모든 프로미스가 이행한 후, 혹은 프로미스가 주어지지 않았을 때 이행하는 Promise를 반환한다.

주어진 프로미스 중 하나가 거부하는 경우, 첫 번째로 거절한 프로미스의 이유를 사용해 자신도 거부

const [movie, videos] = await Promise.all([getMovie(id), getVideos(id)])

 

Suspense
<Suspense>를 사용하면 하위 항목의 로딩이 완료될 때까지 폴백을 표시할 수 있다.

<Suspense fallback={<Loading />}>
  <SomeComponent />
</Suspense>

 

Error Handling

error.js 파일 규칙을 사용하면 중첩된 경로에서 예기치 않은 런타임 오류를 우아하게 처리할 수 있다.

경로 세그먼트 내에 error.js 파일을 추가하고 React 컴포넌트를 내보내서 오류 UI를 만든다.

'use client' // Error components must be Client Components
 
import { useEffect } from 'react'
 
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string }
  reset: () => void
}) {
  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error)
  }, [error])
 
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button
        onClick={
          // Attempt to recover by trying to re-render the segment
          () => reset()
        }
      >
        Try again
      </button>
    </div>
  )
}

 

 

#4 DEPLOYMENT

 

Vercel

https://vercel.com  

 

Vercel: Build and deploy the best Web experiences with The Frontend Cloud – Vercel

Vercel's Frontend Cloud gives developers the frameworks, workflows, and infrastructure to build a faster, more personalized Web.

vercel.com

 

Global Styles

모든 컴포넌트에 전역으로 지정하는 스타일!

ex) app/global.css

 

CSS Modules

Next.js는 .module.css 확장자를 사용하는 CSS 모듈을 기본적으로 지원
CSS 모듈은 고유한 클래스 이름을 자동으로 생성하여 CSS를 로컬로 범위 지정한다. 따라서 충돌 걱정 없이 여러 파일에서 동일한 클래스 이름을 사용할 수 있다!

 

useRouter

useRouter 훅을 사용하면 클라이언트 컴포넌트 내에서 프로그래밍 방식으로 경로를 변경할 수 있다.
*useRouter를 꼭 사용해야 하는 거 아니면 <Link> 컴포넌트를 사용하셈

'use client'
 
import { useRouter } from 'next/navigation'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/dashboard')}>
      Dashboard
    </button>
  )
}

 

toFixed()

이 메서드는 숫자를 고정 소수점 표기법(fixed-point notation)으로 표시 한다.

const numObj = 12345.6789;
numObj.toFixed(1); // Returns '12345.7': 반올림합니다.

 

Metadata

layout.js 또는 page.js 파일에서 메타데이터 개체를 export해서 정적 메타데이터를 정의 한다.

import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: '...',
  description: '...',
}
 
export default function Page() {}

 

generateMetadata function

현재 경로 매개변수, 외부 데이터 또는 상위 세그먼트의 메타데이터와 같은 동적 정보에 따라 달라지는 동적 메타데이터는 메타데이터 객체를 반환하는 generateMetadata 함수를 내보내 설정한다.

import { Metadata, ResolvingMetadata } from 'next'
 
type Props = {
  params: { id: string }
  searchParams: { [key: string]: string | string[] | undefined }
}
 
export async function generateMetadata(
  { params, searchParams }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  // read route params
  const id = params.id
 
  // fetch data
  const product = await fetch(`https://.../${id}`).then((res) => res.json())
 
  // optionally access and extend (rather than replace) parent metadata
  const previousImages = (await parent).openGraph?.images || []
 
  return {
    title: product.title,
    openGraph: {
      images: ['/some-specific-page-image.jpg', ...previousImages],
    },
  }
}
 
export default function Page({ params, searchParams }: Props) {}

 

prefetch

prefetch은 <Link /> 컴포넌트가 사용자의 뷰포트에 들어올 때(처음에 또는 스크롤을 통해) 발생.

Next.js는 클라이언트 측 탐색의 성능을 개선하기 위해 링크된 경로(href로 표시됨)와 데이터를 백그라운드에서 미리 가져와 로드한다다. 프로덕션 환경에서만 활성화됩니다.

true(기본값): 전체 경로와 해당 데이터가 prefetch된다.

 

끝~

참고 웹사이트

https://nextjs.org/

 

Next.js by Vercel - The React Framework

Next.js by Vercel is the full-stack React framework for the web.

nextjs.org