๐Ÿ‘€ Suspensive v2์—์„œ์˜ ๋ณ€๊ฒฝ์„ ํ™•์ธํ•˜์„ธ์š”. ๋”๋ณด๊ธฐ โ†’
๋ฌธ์„œ๋ณด๊ธฐ@suspensive/react-queryuseSuspenseQuery

useSuspenseQuery

์ด hook์˜ return ํƒ€์ž…์—๋Š” isLoading, isError์ด ์—†์Šต๋‹ˆ๋‹ค. <Suspense/>์™€ <ErrorBoundary/>๊ฐ€ ์ด hook์˜ data๋ฅผ ๋ณด์žฅํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ๋˜ํ•œ, ์ด hook์˜ options์—๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ suspense๊ฐ€ true์ž…๋‹ˆ๋‹ค. ํ•„์š”ํ•œ ์ƒˆ options๋Š” @tanstack/react-query์˜ useQuery์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

import { useSuspenseQuery } from '@suspensive/react-query'
 
const Example = () => {
  const query = useSuspenseQuery({
    queryKey,
    queryFn,
  }) // suspense: true๊ฐ€ ๊ธฐ๋ณธ์ž…๋‹ˆ๋‹ค.
 
  // isSuccess์œผ๋กœ type narrowing์ด ํ•„์š”ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  query.data // TData
}
import { useSuspenseQuery } from '@suspensive/react-query'
import { getPost } from './api'

export const Post = ({ postId }: { postId: number }) => {
  const { data } = useSuspenseQuery({
    queryKey: ['posts', postId],
    queryFn: () => getPost(postId),
  })

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  )
}

๋™๊ธฐ

@tanstack/react-query์—์„œ suspense ์˜ต์…˜์„ ์‚ฌ์šฉํ•˜๋ฉด, useQuery๋ฅผ <Suspense/> and <ErrorBoundary/>์™€ ํ•จ๊ป˜ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

import { useQuery } from '@tanstack/react-query'
 
const Example = () => {
  const query = useQuery({
    queryKey,
    queryFn,
    suspense: true,
  })
 
  query.data // TData | undefined
 
  if (query.isSuccess) {
    query.data // TData
  }
}

useQuery์˜ return ํƒ€์ž…(query.data)์€ ์ด ์ปดํฌ๋„ŒํŠธ์˜ ๋ถ€๋ชจ์ธ <Suspense/>์™€ <ErrorBoundary/> ๋•๋ถ„์— ํ•ญ์ƒ ์„ฑ๊ณตํ•œ ๊ฒฝ์šฐ์ผ ๊ฒƒ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ @tanstack/react-query๋Š” ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ํƒ€์ž…์ ์œผ๋กœ ์ด๊ฒƒ์„ ํ‘œํ˜„ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์ด๊ฒƒ์ด @suspensive/react-query๊ฐ€ useSuspenseQuery๋ฅผ ์ œ๊ณตํ•˜๋Š” ์ด์œ ์ž…๋‹ˆ๋‹ค.

๐Ÿ’ก

์„ฑ๊ณตํ•œ ์ผ€์ด์Šค์— ์ง‘์ค‘ํ•˜์„ธ์š”.

์ด์ œ ์šฐ๋ฆฌ๋Š” ์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€์—์„œ fetching์ด ํ•ญ์ƒ ์„ฑ๊ณตํ•˜๋ฏ€๋กœ ์„ฑ๊ณตํ•œ ๊ฒฝ์šฐ์—๋งŒ ์ง‘์ค‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.