NEXT.JS 13버전의 공식문서를 통해 앱라우팅, 데이터패칭을 이해하고 NEXT.JS를 제대로 써보자
page.js
or route.js
파일명을 가진 파일들이 라우팅됨layout
➡️ 여러 페이지에 공유되는 UI(레이아웃 끼리 중첩가능, 리렌더링 ❌)loading
➡️ 로딩페이지, 스켈레톤 구현가능 / Suspense
로도 구현가능(점진적 랜더링)not-found
➡️ 404 화면 구현error
➡️ 중첩 라우팅에서 예상치 못한 에러 핸들링 ➡️ 개별 컴포넌트에 에러라고 띄울수있음(복구도 구현가능)global-error
➡️ 전역으로 에러 핸들링 가능route
➡️ API 생성, 해당 폴더구조로 API호출가능(ex. app/auth)동적으로 API 호출, API 응답 캐싱template
➡️ layout
과 비슷하나 상태가 유지되지않고 페이지 이동시마다 새 인스턴스 생성함(DOM 재생성)fetch
✅async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
Route Handler
내부에 있으면 캐싱❌)// 'force-cache' 는 기본값으로 굳이 써줄필요가 없음
fetch('https://...', { cache: 'force-cache' })
fetch('https://...', { next: { revalidate: 100 } })
export default async function Page() {
const res = await fetch('https://...', { next: { tags: ['collection'] } })
const data = await res.json()
}
fetch('https://...', { cache: 'no-store' })
// or
fetch('https://...', { next: { revalidate: 0 } })
preload
로 최적화 가능import Albums from './albums'
async function getArtist(username: string) {
const res = await fetch(`https://api.example.com/artist/${username}`)
return res.json()
}
async function getArtistAlbums(username: string) {
const res = await fetch(`https://api.example.com/artist/${username}/albums`)
return res.json()
}
export default async function Page({
params: { username },
}: {
params: { username: string }
}) {
// Initiate both requests in parallel
const artistData = getArtist(username)
const albumsData = getArtistAlbums(username)
// Wait for the promises to resolve
const [artist, albums] = await Promise.all([artistData, albumsData])
return (
<>
<h1>{artist.name}</h1>
<Albums list={albums}></Albums>
</>
)
}
async function Playlists({ artistID }: { artistID: string }) {
// Wait for the playlists
const playlists = await getArtistPlaylists(artistID)
return (
<ul>
{playlists.map((playlist) => (
<li key={playlist.id}>{playlist.name}</li>
))}
</ul>
)
}
export default async function Page({
params: { username },
}: {
params: { username: string }
}) {
// Wait for the artist
const artist = await getArtist(username)
return (
<>
<h1>{artist.name}</h1>
<Suspense fallback={<div>Loading...</div>}>
<Playlists artistID={artist.id} />
</Suspense>
</>
)
}
layout
, page
자동 Data Fetching 및 중복 처리:Data Fetching 시 요청 중복 자동처리로 성능향상fetch() API
: fetch() API
기반 Data Fetching / async/await를 사용하여 서버 컴포넌트를 통해 Data Fetching