Next.js 서버 액션은 서버 데이터를 가져오는 용도로 사용하기에 적합하지 않다. React 공식문서에서는 다음과 같이 말하고 있다.
Server Functions are designed for mutations that update server-side state; they are not recommended for data fetching. Accordingly, frameworks implementing Server Functions typically process one action at a time and do not have a way to cache the return value.
서버 액션이 여러 호출되면 바로 실행되는 대신 큐에 쌓이고 순차적으로 처리된다. 이미 실행된 서버 액션은 이후 취소할 수 없다.
이에 서버 액션을 데이터 가져오기로 활용하면 끔찍해지는 UX가 생길 수 있는데, 예를 들어 페이지의 목록 검색 화면에서 검색 후 데이터를 가져오는 상황에 않았다고 다른 화면으로 네비게이션이 불가능한 것은 일반적인 경험이 아니다.
이러면 RSC를 통해 무한 스크롤을 구현하지 못하는가? 에 대해서 의문이 생길 수 있는데 여기에 대해서 대안을 발견했다.
function ServerComponent({ searchParams }) {
const page = parseInt((await searchParams).page ?? "1", 10)
const items = await getItems(page)
return (
<Collection id={page}>
{items.map(item => <InfiniteListItem key={item.id} {...items} />)}
</Collection>
)
}
"use client"
function Collection({ id, children }) {
const [collection, setCollection] = useState(new Map([[id, children]]))
const [lastId, setLastId] = useState(id)
if (id !== lastId) {
setCollection(oldCollection => {
const newCollection = new Map(oldCollection)
newCollection.set(id, children)
return newCollection
})
setLastId(id)
}
return Array
.from(collection.entries())
.map(
([id, children]) => <Fragment key={id}>{children}</Fragment>
)
}
대충 이런 꼴이다. 이러고 page를 증가시키거나 감소시키는건 intesection observer나 특정 엘리먼트의 onClick 이벤트 따위를 의존하면 된다. 이러면 데이터 가져오기 패턴을 RSC 형태로 의존할 수 있다. InfiniteListItem
는 서버컴포넌트, 클라이언트컴포넌트 무엇으로 구현하더라도 상관없다. 가령 아래와 같은 식:
function ServerComponent({ searchParams }) {
const page = parseInt((await searchParams).page ?? "1", 10)
const { items, hasNext } = await getItems(page)
return (
<div>
<Collection id={page}>
{items.map(item => <InfiniteListItem key={item.id} {...items} />)}
</Collection>
{hasNext && (
<IntersectionObserver nextUrl={`/?page=${page + 1}`} />
)}
</div>
)
}
검색 조건이나 검색어에 따라 상태를 초기화시키려면 다음과 같이 표현하면 된다.
function ServerComponent({ searchParams }) {
const page = parseInt((await searchParams).page ?? "1", 10)
const query = parseInt((await searchParams).query ?? "")
const { items, hasNext } = await getItems(page, query)
return (
<div>
<Form action="/">
<input name="query" />
<button />
</Form>
<Collection id={page} key={query}>
{items.map(item => <InfiniteListItem key={item.id} {...items} />)}
</Collection>
{hasNext && (
<IntersectionObserver nextUrl={`/?page=${page + 1}&query=${query}`} />
)}
</div>
)
}
매우 PHP스럽고, 암묵적이기도 하다. 다만 RSC의 데이터 가져오기 패턴을 활용하면서 기존 컴포넌트를 최대한 재사용할 수 있게 된다는 점이 좋다.