Client-side data fetching
Basic Features > Data Fetching > Client-side data fetching
component 레벨에서 클라이언트 측 데이터 가져오기를 사용할 수 있습니다.
Client-side data fetching은 페이지에 SEO indexing 이 필요하지 않거나, 데이터를 미리 렌더링할 필요가 없거나, 콘텐츠를 자주 업데이트해야할 때 유용합니다.
Page 레벨에서 수행하면 런타임에 데이터를 가져오고 데이터가 변경되면 페이지 내용이 업데이트 됩니다.
Component 레벨의 경우 component 마운트시 데이터를 가져오고 데이터가 변경되면 component 내용이 업데이트 됩니다.
Client-side에서 데이터 가져오는 방법은 애플리케이션의 성능과 페이지의 로드 속도에 영향을 미칠 수 있습니다. server-side data fetching 과 달리 데이터가 캐싱되지 않습니다.
useEffect 사용하기 (Client-side data fetching with useEffect)
useEffect를 이용하여 client-side data fetching 을 하는 코드입니다.
function Profile() {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
fetch('api/profile-data')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}, [])
if (isLoading) return <p>Loading...</p>
if (!profileData) return <p>No profile data</p>
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}
Client-side data fetching with SWR
SWR은 data fetching 을 위한 React hook 라이브러리입니다.
import useSWR from 'swr'
const fetcher = (...args) => fetch(...args).then((res) => res.json())
function Profile() {
const { data, error } = useSWR('/api/profile-data', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}
Data Fetching: Client side | Next.js
Learn about client-side data fetching, and how to use SWR, a data fetching React hook library that handles caching, revalidation, focus tracking, refetching on interval and more.
nextjs.org
댓글