https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
https://nextjs.org/docs/app/building-your-application/data-fetching/patterns
App router 기준 Next.js에서 data fetching을 요약하자면 다음과 같다.
- Server Component에서 - 서버 측에서 작동하기 때문에, effect 없이 그냥 fetch 사용 가능하며, 심지어 바로 DB query 작성도 가능하다. 코드가 클라이언트에 노출되지 않기 때문에 안심하고 API key 등을 사용할 수 있다.
- 주로 서버측에서 GET 메소드 요청이 필요할때 사용한다고 볼 수 있을 것이다.
- Server Actions - data mutation(POST, PUT, DELETE 등)이 필요할때 사용할 수 있다.
- ‘use server’ directive를 사용하면 server action으로 취급된다.
- server component, client component에서 둘다 사용할 수 있지만, client component에서 사용할때는 해당 파일 안에서 바로 ‘use server’를 사용할 수는 없고, import 해서 사용해야 한다.
- Client Component에서 - 기존 리액트 컴포넌트에서 처럼 effect 훅 내부에서 사용하면 된다.
- 주로 이벤트 핸들러에 의한 서버 요청 동작이 필요할때 이 패턴을 사용하게 된다.
- 개인적인 경험으로는 서버에서 응답에 Set Cookie를 포함할때, server action을 사용하면 브라우저에 쿠키 셋팅이 되지 않아서 effect hook을 사용했던 경험이 있다.
Data Fetching, Caching and Revalidating
Data fetching is a core part of any application. This page goes through how you can fetch, cache, and revalidate data in React and Next.js.
There are four ways you can fetch data:
- On the server, with
fetch
- On the server, with third-party libraries
- On the client, via a Route Handler
- On the client, with third-party libraries. (e.g. SWR, TanStack Query)
Server Actions and Mutations
Patterns and Best Practices
Fetching data on the server
Next.js는 가능할때면 언제나 Server Component에서 데이터 페칭을 하는 것을 권장한다고 한다(물론 필요할때는 Client Component를 적절히 활용해야 겠지만). 이는 다음과 같은 장점들이 있다.