diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md index c5f06e99a..1d90a83d6 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -4,7 +4,7 @@ title: use -`use`는 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)나 [Context](/learn/passing-data-deeply-with-context)와 같은 데이터를 참조하는 React API입니다. +`use`는 렌더링 중에 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)나 [Context](/learn/passing-data-deeply-with-context)와 같은 데이터를 참조하는 React API입니다. ```js const value = use(resource); @@ -20,7 +20,7 @@ const value = use(resource); ### `use(context)` {/*use-context*/} -컴포넌트에서 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)나 [Context](/learn/passing-data-deeply-with-context)와 같은 데이터를 참조하려면 `use`를 사용하세요. +[Context](/learn/passing-data-deeply-with-context)의 값을 읽으려면 Context를 전달해 `use`를 호출하세요. [`useContext`](/reference/react/useContext)와 달리 `use`는 `if`와 같은 조건문과 반복문 내부에서 호출할 수 있습니다. ```js import { use } from 'react'; @@ -30,31 +30,59 @@ function Button() { // ... ``` -다른 React Hook과 달리 `use`는 `if`와 같은 조건문과 반복문 내부에서 호출할 수 있습니다. 다만, 다른 React Hook과 같이 `use`는 컴포넌트 또는 Hook에서만 호출해야 합니다. +[아래 예시를 참고하세요.](#usage-context) -Promise와 함께 호출될 때 `use` API는 [`Suspense`](/reference/react/Suspense) 및 [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary)와 통합됩니다. `use`에 전달된 Promise가 대기Pending하는 동안 `use`를 호출하는 컴포넌트는 *Suspend*됩니다. `use`를 호출하는 컴포넌트가 Suspense 경계로 둘러싸여 있으면 Fallback이 표시됩니다. Promise가 리졸브되면 Suspense Fallback은 `use` API가 반환한 컴포넌트로 대체됩니다. `use`에 전달된 Promise가 Reject되면 가장 가까운 Error Boundary의 Fallback이 표시됩니다. +#### 매개변수 {/*context-parameters*/} -[아래 예시를 참고하세요.](#usage) +* `context`: [`createContext`](/reference/react/createContext)로 생성한 [Context](/learn/passing-data-deeply-with-context)입니다. -#### 매개변수 {/*parameters*/} +#### 반환값 {/*context-returns*/} -* `resource`: 참조하려는 데이터입니다. 데이터는 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)나 [Context](/learn/passing-data-deeply-with-context)일 수 있습니다. +전달한 Context의 값을 반환합니다. 이 값은 호출하는 컴포넌트 위에 있는 가장 가까운 Context Provider에 따라 정해집니다. Provider가 없으면 반환된 값은 [`createContext`](/reference/react/createContext)에 전달한 `defaultValue`가 됩니다. -#### 반환값 {/*returns*/} +#### 주의 사항 {/*context-caveats*/} -`use` Hook은 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)나 [Context](/learn/passing-data-deeply-with-context)에서 참조한 값을 반환합니다. +* `use`는 컴포넌트나 Hook 내부에서만 호출할 수 있습니다. +* [서버 컴포넌트](/reference/rsc/server-components)에서는 `use`로 Context를 읽을 수 없습니다. -#### 주의 사항 {/*caveats*/} +--- + +### `use(promise)` {/*use-promise*/} + +[Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)의 리졸브된 값을 읽으려면 Promise를 전달해 `use`를 호출하세요. Promise가 대기Pending 중인 동안 `use`를 호출하는 컴포넌트는 *일시 중단*Suspend됩니다. 이름과 달리 `use`는 Hook이 아닙니다. Hook과 다르게 `if`와 같은 조건문과 반복문 내부에서 호출할 수 있습니다. + +```js +import { use } from 'react'; + +function MessageComponent({ messagePromise }) { + const message = use(messagePromise); + // ... +``` + +`use`를 호출하는 컴포넌트가 [Suspense](/reference/react/Suspense) 경계로 둘러싸여 있으면 Promise가 대기 중인 동안 Fallback이 표시됩니다. Promise가 리졸브되면 Suspense Fallback은 `use`가 반환한 데이터를 사용해 렌더링된 컴포넌트로 대체됩니다. Promise가 거부되면 가장 가까운 [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary)의 Fallback이 표시됩니다. + +[아래 예시를 참고하세요.](#usage-promises) + +#### 매개변수 {/*promise-parameters*/} + +* `promise`: 리졸브된 값을 읽으려는 [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise)입니다. 리렌더링 간에 같은 인스턴스를 재사용할 수 있도록 Promise를 [캐시](#caching-promises-for-client-components)해야 합니다. -* `use` API는 컴포넌트나 Hook 내부에서 호출되어야 합니다. -* [서버 컴포넌트](/reference/rsc/use-server)에서 데이터를 가져올 때는 `use`보다 `async` 및 `await`을 사용합니다. `async` 및 `await`은 `await`이 호출된 시점부터 렌더링을 시작하는 반면, `use`는 데이터가 리졸브된 후 컴포넌트를 리렌더링합니다. -* [클라이언트 컴포넌트](/reference/rsc/use-client)에서 Promise를 생성하는 것보다 [서버 컴포넌트](/reference/rsc/use-server)에서 Promise를 생성하여 클라이언트 컴포넌트에 전달하는 것이 좋습니다. 클라이언트 컴포넌트에서 생성된 Promise는 렌더링할 때마다 다시 생성됩니다. 서버 컴포넌트에서 클라이언트 컴포넌트로 전달된 Promise는 리렌더링 전반에 걸쳐 안정적입니다. [예시를 확인하세요](#streaming-data-from-server-to-client). +#### 반환값 {/*promise-returns*/} + +Promise의 리졸브된 값을 반환합니다. + +#### 주의 사항 {/*promise-caveats*/} + +* `use`는 컴포넌트나 Hook 내부에서만 호출할 수 있습니다. +* `use`는 try-catch 블록 내부에서 호출할 수 없습니다. 대신 컴포넌트를 [Error Boundary](#displaying-an-error-with-an-error-boundary)로 래핑해 오류를 포착하고 Fallback을 표시하세요. +* `use`에 전달하는 Promise는 리렌더링 간에 같은 Promise 인스턴스를 재사용할 수 있도록 캐시해야 합니다. [아래 Promise 캐싱 방법을 참고하세요.](#caching-promises-for-client-components) +* 서버 컴포넌트에서 클라이언트 컴포넌트로 Promise를 전달할 때 리졸브된 값은 [직렬화 가능](/reference/rsc/use-client#serializable-types)해야 합니다. --- ### `use(browser())` {/*use-browser*/} -Call `use` with the value returned by [`browser`](/reference/react-dom/browser) in a component that should only render in the browser: +브라우저에서만 렌더링되어야 하는 컴포넌트에서 [`browser`](/reference/react-dom/browser)가 반환한 값을 전달해 `use`를 호출하세요. ```js import { use } from 'react'; @@ -66,30 +94,30 @@ function BrowserOnly() { } ``` -During server rendering, the component calling `use(browser())` suspends and React includes the closest [``](/reference/react/Suspense) boundary's fallback in the HTML. In the browser, `use(browser())` returns `undefined`, so the component renders normally. +서버 렌더링 동안 `use(browser())`를 호출하는 컴포넌트는 일시 중단되고, React는 가장 가까운 [``](/reference/react/Suspense) 경계의 Fallback을 HTML에 포함합니다. 브라우저에서는 `use(browser())`가 `undefined`를 반환하므로 컴포넌트가 정상적으로 렌더링됩니다. -[See an example below.](#rendering-a-component-only-in-the-browser) +[아래 예시를 참고하세요.](#rendering-a-component-only-in-the-browser) -#### Parameters {/*browser-parameters*/} +#### 매개변수 {/*browser-parameters*/} -* `browserValue`: The value returned by [`browser`](/reference/react-dom/browser). +* `browserValue`: [`browser`](/reference/react-dom/browser)가 반환한 값입니다. -#### Returns {/*browser-returns*/} +#### 반환값 {/*browser-returns*/} -`use(browser())` returns `undefined` in the browser. +`use(browser())`는 브라우저에서 `undefined`를 반환합니다. -#### Caveats {/*browser-caveats*/} +#### 주의 사항 {/*browser-caveats*/} -* The component calling `use(browser())` must be inside a `` boundary during server rendering. Without one, server rendering fails. -* In a React Server Components app, `use(browser())` must be called from a [Client Component](/reference/rsc/use-client), not a [Server Component](/reference/rsc/server-components). +* `use(browser())`를 호출하는 컴포넌트는 서버 렌더링 동안 `` 경계 내부에 있어야 합니다. 경계가 없으면 서버 렌더링이 실패합니다. +* React 서버 컴포넌트 앱에서는 `use(browser())`를 [서버 컴포넌트](/reference/rsc/server-components)가 아니라 [클라이언트 컴포넌트](/reference/rsc/use-client)에서 호출해야 합니다. --- -## 사용법 {/*usage*/} +## Context 사용법 {/*usage-context*/} ### `use`를 사용하여 Context 참조하기 {/*reading-context-with-use*/} -[Context](/learn/passing-data-deeply-with-context)가 `use`에 전달되면 [`useContext`](/reference/react/useContext)와 유사하게 작동합니다. `useContext`는 컴포넌트의 최상위 수준에서 호출해야 하지만, `use`는 `if`와 같은 조건문이나 `for`와 같은 반복문 내부에서 호출할 수 있습니다. `use`는 유연하므로 `useContext`보다 선호됩니다. +[Context](/learn/passing-data-deeply-with-context)가 `use`에 전달되면 [`useContext`](/reference/react/useContext)와 유사하게 작동합니다. `useContext`는 컴포넌트의 최상위 수준에서 호출해야 하지만, `use`는 `if`와 같은 조건문이나 `for`와 같은 반복문 내부에서 호출할 수 있습니다. ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react'; @@ -99,9 +127,9 @@ function Button() { // ... ``` -`use`는 전달한 Context의 Context Value를 반환합니다. Context 값을 결정하기 위해 React는 컴포넌트 트리를 탐색하고 **위에서 가장 가까운 Context Provider**를 찾습니다. +`use`는 전달한 Context의 Context Value를 반환합니다. Context 값을 결정하기 위해 React는 컴포넌트 트리를 탐색하고 해당 Context에 대해 **위에서 가장 가까운 Context Provider**를 찾습니다. -Context를 `Button`에 전달하려면 `Button` 또는 상위 컴포넌트 중 하나를 Context Provider로 래핑합니다. +Context를 `Button`에 전달하려면 `Button` 또는 상위 컴포넌트 중 하나를 해당 Context Provider로 래핑합니다. ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -241,23 +269,23 @@ function Profile() { } ``` -Reading the value requires two `use` calls because the context value itself isn't awaited. See [Before you use context](/learn/passing-data-deeply-with-context#before-you-use-context) for alternatives to consider before reaching for context. +`use(context)`는 Context 값 자체를 기다리지 않으므로 값을 읽으려면 `use`를 두 번 호출해야 합니다. Context보다 먼저 고려할 만한 대안은 [Context를 사용하기 전에 고려할 것](/learn/passing-data-deeply-with-context#before-you-use-context)을 참고하세요. -Wrap the components that read the Promise in a [Suspense](/reference/react/Suspense) boundary so only that subtree suspends while the Promise is pending. See [Usage (Promises)](#usage-promises) below for more on reading Promises with `use`. +Promise가 대기 중인 동안 해당 서브트리만 일시 중단되도록 Promise를 읽는 컴포넌트를 [Suspense](/reference/react/Suspense) 경계로 래핑하세요. `use`로 Promise를 읽는 방법은 아래 [Promise 사용법](#usage-promises)에서 자세히 알아보세요. -When this pattern is used with [Server Components](/reference/rsc/server-components), refetching the Promise requires refetching the Server Component that sets the Promise in context. Avoid setting the Promise in context high in the tree, since that would refetch large parts of the app unnecessarily. +이 패턴을 [서버 컴포넌트](/reference/rsc/server-components)와 함께 사용할 때 Promise를 다시 가져오려면 Context에 Promise를 설정하는 서버 컴포넌트를 다시 불러와야 합니다. 트리 상단에서 Context에 Promise를 설정하면 앱의 많은 부분을 불필요하게 다시 불러오게 되므로 피하세요. --- -## Usage (Promises) {/*usage-promises*/} +## Promise 사용법 {/*usage-promises*/} -### Reading a Promise with `use` {/*reading-a-promise-with-use*/} +### `use`로 Promise 읽기 {/*reading-a-promise-with-use*/} -Call `use` with a Promise to read its resolved value. The component will [suspend](/reference/react/Suspense) while the Promise is pending. +리졸브된 값을 읽으려면 Promise를 전달해 `use`를 호출하세요. Promise가 대기 중인 동안 컴포넌트는 [일시 중단](/reference/react/Suspense)됩니다. ```js [[1, 4, "use(albumsPromise)"]] import { use } from 'react'; @@ -276,13 +304,13 @@ function Albums({ albumsPromise }) { } ``` -Wrap the component that calls `use` in a [Suspense](/reference/react/Suspense) boundary so React can show a fallback while the Promise is pending. The closest Suspense boundary above the suspending component shows its fallback. Once the Promise resolves, React reads the value with `use` and replaces the fallback with the rendered component. +Promise가 대기 중인 동안 React가 Fallback을 표시할 수 있도록 `use`를 호출하는 컴포넌트를 [Suspense](/reference/react/Suspense) 경계로 래핑하세요. 일시 중단된 컴포넌트 위에 있는 가장 가까운 Suspense 경계가 Fallback을 표시합니다. Promise가 리졸브되면 React는 `use`로 값을 읽고 Fallback을 렌더링된 컴포넌트로 대체합니다. - + -#### Fetching data with `use` {/*fetching-data-with-use*/} +#### `use`로 데이터 가져오기 {/*fetching-data-with-use*/} -In this example, `Albums` calls `use` with a cached Promise. The component suspends while the Promise is pending, and React displays the nearest Suspense fallback. Rejected Promises propagate to the nearest [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). +이 예시에서 `Albums`는 캐시된 Promise를 전달해 `use`를 호출합니다. Promise가 대기 중인 동안 컴포넌트는 일시 중단되고 React는 가장 가까운 Suspense Fallback을 표시합니다. 거부된 Promise는 가장 가까운 [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary)로 전파됩니다. @@ -320,9 +348,9 @@ function Loading() { ``` ```js src/data.js hidden -// Note: the way you would do data fetching depends on -// the framework that you use together with Suspense. -// Normally, the caching logic would be inside a framework. +// Note: 데이터 페칭 방법은 +// Suspense와 함께 사용하는 프레임워크에 따라 달라집니다. +// 일반적으로 캐싱 로직은 프레임워크 내부에 있습니다. let cache = new Map(); @@ -342,7 +370,7 @@ async function getData(url) { } async function getAlbums() { - // Add a fake delay to make waiting noticeable. + // 대기 시간을 눈에 띄게 만들기 위해 가짜 지연을 추가합니다. await new Promise(resolve => { setTimeout(resolve, 1000); }); @@ -383,9 +411,9 @@ async function getAlbums() { -#### Fetching data with `useEffect` {/*fetching-data-with-useeffect*/} +#### `useEffect`로 데이터 가져오기 {/*fetching-data-with-useeffect*/} -Before `use`, a common approach was to fetch data in an Effect and update state when the data arrives. Compared to `use`, this approach requires managing loading and error states manually. For more details on why fetching in an Effect is discouraged, see [You Might Not Need an Effect](/learn/you-might-not-need-an-effect#fetching-data). +`use`가 나오기 전에는 Effect에서 데이터를 가져오고 데이터가 도착하면 state를 업데이트하는 방식을 흔히 사용했습니다. `use`와 비교하면 이 방식은 로딩 상태와 오류 상태를 직접 관리해야 합니다. Effect에서 데이터를 가져오는 방식을 권장하지 않는 이유는 [Effect가 필요하지 않은 경우](/learn/you-might-not-need-an-effect#fetching-data)에서 자세히 알아보세요. @@ -432,7 +460,7 @@ export default function App() { ```js src/data.js hidden export async function fetchAlbums() { - // Add a fake delay to make waiting noticeable. + // 대기 시간을 눈에 띄게 만들기 위해 가짜 지연을 추가합니다. await new Promise(resolve => { setTimeout(resolve, 1000); }); @@ -465,22 +493,22 @@ export async function fetchAlbums() { -##### Promises passed to `use` must be cached {/*promises-must-cached*/} +##### `use`에 전달하는 Promise는 캐시해야 합니다 {/*promises-must-cached*/} -Promises created during render are recreated on every render, which causes React to show the Suspense fallback repeatedly and prevents content from appearing. +렌더링 중에 생성한 Promise는 렌더링할 때마다 다시 생성되므로 React가 Suspense Fallback을 반복해서 표시하고 콘텐츠가 나타나지 않습니다. ```js function Albums() { - // 🔴 `fetch` creates a new Promise on every render. + // 🔴 `fetch`는 렌더링할 때마다 새로운 Promise를 생성합니다. const albums = use(fetch('/albums')); // ... } ``` -Instead, pass a Promise from a cache, a [Suspense-enabled framework](/reference/react/Suspense#suspense-enabled-frameworks), or a Server Component: +대신 캐시, [Suspense를 지원하는 프레임워크](/reference/react/Suspense#suspense-enabled-frameworks) 또는 서버 컴포넌트에서 받은 Promise를 전달하세요. ```js -// ✅ fetchData reads the Promise from a cache. +// ✅ fetchData는 캐시에서 Promise를 읽습니다. const albums = use(fetchData('/albums')); ``` @@ -488,34 +516,34 @@ const albums = use(fetchData('/albums')); -#### Why are Promises recreated on every render? {/*why-promises-recreated*/} +#### 왜 Promise는 렌더링할 때마다 다시 생성되나요? {/*why-promises-recreated*/} -[React doesn't preserve state for renders that suspended before mounting](/reference/react/Suspense#caveats). After each suspension, React retries rendering from scratch, so any Promise created during render is recreated. +[React는 마운트되기 전에 일시 중단된 렌더링의 state를 보존하지 않습니다](/reference/react/Suspense#caveats). 일시 중단될 때마다 React는 처음부터 다시 렌더링을 시도하므로 렌더링 중에 생성한 Promise는 모두 다시 생성됩니다. -Common ways a Promise can be unintentionally recreated during render: +다음은 렌더링 중에 Promise가 의도치 않게 다시 생성되는 흔한 경우입니다. ```js function Albums() { - // 🔴 `fetch` creates a new Promise on every render. + // 🔴 `fetch`는 렌더링할 때마다 새로운 Promise를 생성합니다. const albums = use(fetch('/albums')); - // 🔴 Uncached `async` function calls create a new Promise on every render. + // 🔴 캐시되지 않은 `async` 함수를 호출하면 렌더링할 때마다 새로운 Promise가 생성됩니다. const albums = use((async () => { const res = await fetch('/albums'); return res.json(); })()); - // 🔴 Adding `.then` returns a new Promise on every render, - // even if `fetchData` is cached. + // 🔴 `.then`을 붙이면 `fetchData`가 캐시되어 있더라도 + // 렌더링할 때마다 새로운 Promise가 반환됩니다. const albums = use(fetchData('/albums').then(res => res.json())); // ... } ``` -Ideally, Promises are created before rendering, such as in an event handler, a route loader, or a Server Component, and passed to the component that calls `use`. Fetching lazily in render delays network requests and can create waterfalls. +이상적으로는 이벤트 핸들러, 라우트 로더, 서버 컴포넌트 같은 곳에서 렌더링 전에 Promise를 생성하고 `use`를 호출하는 컴포넌트에 전달합니다. 렌더링할 때가 되어서야 데이터를 가져오면 네트워크 요청이 늦어지고 워터폴Waterfall이 생길 수 있습니다. ```js -// ✅ fetchData reads the Promise from a cache. +// ✅ fetchData는 캐시에서 Promise를 읽습니다. const albums = use(fetchData('/albums')); ``` @@ -523,12 +551,12 @@ const albums = use(fetchData('/albums')); --- -### Caching Promises for Client Components {/*caching-promises-for-client-components*/} +### 클라이언트 컴포넌트에서 Promise 캐싱하기 {/*caching-promises-for-client-components*/} -Promises passed to `use` in Client Components must be cached so the same Promise instance is reused across re-renders. If a new Promise is created directly in render, React will display the Suspense fallback on every re-render. +클라이언트 컴포넌트에서 `use`에 전달하는 Promise는 리렌더링 간에 같은 Promise 인스턴스를 재사용할 수 있도록 캐시해야 합니다. 렌더링 중에 새로운 Promise를 직접 생성하면 React는 리렌더링할 때마다 Suspense Fallback을 표시합니다. ```js -// ✅ Cache the Promise so the same one is reused across renders +// ✅ 렌더링 간에 같은 Promise를 재사용하도록 Promise를 캐시합니다 let cache = new Map(); export function fetchData(url) { @@ -539,15 +567,15 @@ export function fetchData(url) { } ``` -The `fetchData` function returns the same Promise each time it's called with the same URL. When `use` receives the same Promise on a re-render, it reads the already-resolved value synchronously without suspending. +`fetchData` 함수는 같은 URL로 호출될 때마다 같은 Promise를 반환합니다. 리렌더링 시 `use`가 같은 Promise를 받으면 일시 중단하지 않고 이미 리졸브된 값을 동기적으로 읽습니다. -The way you cache Promises depends on the framework you use with Suspense. Frameworks typically provide built-in caching mechanisms. If you don't use a framework, you can use a simple module-level cache like the one above, or a [Suspense-enabled data source](/reference/react/Suspense#what-activates-a-suspense-boundary). +Promise를 캐시하는 방법은 Suspense와 함께 사용하는 프레임워크에 따라 다릅니다. 프레임워크는 일반적으로 캐싱 메커니즘을 내장하고 있습니다. 프레임워크를 사용하지 않는다면 위와 같은 간단한 모듈 수준 캐시나 [Suspense를 지원하는 데이터 소스](/reference/react/Suspense#what-activates-a-suspense-boundary)를 사용할 수 있습니다. -In the example below, clicking "Re-render" updates state in `App` and triggers a re-render. Because `fetchData` returns the same cached Promise, `Albums` reads the value synchronously instead of showing the Suspense fallback again. +아래 예시에서 "Re-render"를 클릭하면 `App`의 state가 업데이트되어 리렌더링이 발생합니다. `fetchData`가 캐시된 같은 Promise를 반환하므로 `Albums`는 Suspense Fallback을 다시 표시하지 않고 값을 동기적으로 읽습니다. @@ -585,9 +613,9 @@ function Albums() { ``` ```js src/data.js hidden -// Note: the way you would do data fetching depends on -// the framework that you use together with Suspense. -// Normally, the caching logic would be inside a framework. +// Note: 데이터 페칭 방법은 +// Suspense와 함께 사용하는 프레임워크에 따라 달라집니다. +// 일반적으로 캐싱 로직은 프레임워크 내부에 있습니다. let cache = new Map(); @@ -607,7 +635,7 @@ async function getData(url) { } async function getAlbums() { - // Add a fake delay to make waiting noticeable. + // 대기 시간을 눈에 띄게 만들기 위해 가짜 지연을 추가합니다. await new Promise(resolve => { setTimeout(resolve, 1000); }); @@ -632,9 +660,9 @@ async function getAlbums() { -#### How to implement a promise cache {/*how-to-implement-a-promise-cache*/} +#### Promise 캐시를 구현하는 방법 {/*how-to-implement-a-promise-cache*/} -A basic cache stores the Promise keyed by URL so the same instance is reused across renders. To also avoid unnecessary Suspense fallbacks when data is already available, you can set `status` and `value` (or `reason`) fields on the Promise. React checks these fields when `use` is called: if `status` is `'fulfilled'`, it reads `value` synchronously without suspending. If `status` is `'rejected'`, it throws `reason`. If the field is missing or `'pending'`, it suspends. +기본적인 캐시는 렌더링 간에 같은 인스턴스를 재사용할 수 있도록 URL을 키로 Promise를 저장합니다. 데이터가 이미 준비되어 있을 때 불필요한 Suspense Fallback도 피하려면 Promise에 `status`와 `value`(또는 `reason`) 필드를 설정할 수 있습니다. React는 `use`가 호출될 때 이 필드를 확인합니다. `status`가 `'fulfilled'`이면 일시 중단하지 않고 `value`를 동기적으로 읽습니다. `status`가 `'rejected'`이면 `reason`을 던집니다. 필드가 없거나 `'pending'`이면 일시 중단합니다. ```js let cache = new Map(); @@ -659,21 +687,21 @@ function fetchData(url) { } ``` -This is primarily useful for library authors building Suspense-compatible data layers. React will set the `status` field itself on Promises that don't have it, but setting it yourself avoids an extra render when the data is already available. +이 방식은 주로 Suspense와 호환되는 데이터 레이어를 만드는 라이브러리 작성자에게 유용합니다. `status` 필드가 없는 Promise에는 React가 자체적으로 필드를 설정하지만, 직접 설정하면 데이터가 이미 준비되어 있을 때 추가 렌더링을 피할 수 있습니다. -This cache pattern is the foundation for [re-fetching data](#re-fetching-data-in-client-components) (where changing the cache key triggers a new fetch) and [preloading data on hover](#preloading-data-on-hover) (where calling `fetchData` early means the Promise may already be resolved by the time `use` reads it). +이 캐시 패턴은 [데이터 다시 가져오기](#re-fetching-data-in-client-components)와 [호버 시 데이터 미리 불러오기](#preloading-data-on-hover)의 기반이 됩니다. 다시 가져오기에서는 캐시 키를 바꾸면 데이터를 새로 가져오고, 미리 불러오기에서는 `fetchData`를 일찍 호출하므로 `use`가 읽을 때쯤 Promise가 이미 리졸브되어 있을 수 있습니다. -##### Don't skip calling `use` based on whether a Promise is already settled. {/*conditional-use*/} +##### Promise가 이미 처리Settled되었는지에 따라 `use` 호출을 건너뛰지 마세요. {/*conditional-use*/} -Unlike other hooks, `use` can be called inside conditions and loops — but it must always be called for the Promise itself. Never read `promise.status` or `promise.value` directly to bypass `use`; always pass the Promise to `use` and let React handle it. +다른 Hook과 달리 `use`는 조건문과 반복문 내부에서 호출할 수 있지만, Promise는 항상 `use`로 읽어야 합니다. `use`를 우회하려고 `promise.status`나 `promise.value`를 절대 직접 읽지 마세요. 항상 Promise를 `use`에 전달하고 React가 처리하도록 하세요. ```js -// 🔴 Don't bypass `use` by reading promise status directly +// 🔴 Promise 상태를 직접 읽어 `use`를 우회하지 마세요 if (promise.status === 'fulfilled') { return promise.value; } @@ -681,19 +709,19 @@ const value = use(promise); ``` ```js -// ✅ Pass the promise to `use` and let React track the promise +// ✅ Promise를 `use`에 전달해 React가 Promise를 추적하도록 합니다 const value = use(promise); ``` -Bypassing `use` this way can break React Suspense optimizations and Suspense features for React DevTools. You can `use(promise)` conditionally, but don't conditionally `use(promise)` based on the promise itself. +이런 식으로 `use`를 우회하면 React의 Suspense 최적화와 React DevTools의 Suspense 기능이 깨질 수 있습니다. `use(promise)`를 조건부로 호출할 수는 있지만, Promise 자체를 기준으로 `use(promise)` 호출 여부를 정하지는 마세요. --- -### Re-fetching data in Client Components {/*re-fetching-data-in-client-components*/} +### 클라이언트 컴포넌트에서 데이터 다시 가져오기 {/*re-fetching-data-in-client-components*/} -To refresh data at the same URL (for example, with a "Refresh" button), invalidate the cache entry and start a new fetch inside a [`startTransition`](/reference/react/startTransition). Store the resulting Promise in state to trigger a re-render. While the new Promise is pending, React keeps showing the existing content because the update is inside a Transition. +같은 URL의 데이터를 새로 고치려면(예를 들어 "Refresh" 버튼으로) [`startTransition`](/reference/react/startTransition) 내부에서 캐시 항목을 무효화하고 데이터를 다시 가져오세요. 반환된 Promise를 state에 저장해 리렌더링을 일으키세요. 업데이트가 Transition 내부에 있으므로 새로운 Promise가 대기 중인 동안 React는 기존 콘텐츠를 계속 표시합니다. ```js function App() { @@ -709,7 +737,7 @@ function App() { } ``` -`refetchData` clears the old cache entry and starts a new fetch at the same URL. Storing the resulting Promise in state triggers a re-render inside the Transition. On re-render, `Albums` receives the new Promise and `use` suspends on it while React keeps showing the old content. +`refetchData`는 이전 캐시 항목을 지우고 같은 URL에서 데이터를 새로 가져오기 시작합니다. 반환된 Promise를 state에 저장하면 Transition 내부에서 리렌더링이 발생합니다. 리렌더링되면 `Albums`가 새로운 Promise를 받습니다. `use`는 이 Promise를 기다리며 일시 중단되고, 그동안 React는 이전 콘텐츠를 계속 표시합니다. @@ -766,9 +794,9 @@ function Loading() { ``` ```js src/data.js hidden -// Note: the way you would do data fetching depends on -// the framework that you use together with Suspense. -// Normally, the caching logic would be inside a framework. +// Note: 데이터 페칭 방법은 +// Suspense와 함께 사용하는 프레임워크에 따라 달라집니다. +// 일반적으로 캐싱 로직은 프레임워크 내부에 있습니다. let cache = new Map(); @@ -793,7 +821,7 @@ async function getData(url) { } async function getAlbums() { - // Add a fake delay to make waiting noticeable. + // 대기 시간을 눈에 띄게 만들기 위해 가짜 지연을 추가합니다. await new Promise(resolve => { setTimeout(resolve, 1000); }); @@ -830,15 +858,15 @@ button { margin-bottom: 10px; } -Frameworks that support Suspense typically provide their own caching and invalidation mechanisms. The custom cache above is useful for understanding the pattern, but in practice prefer your framework's data fetching solution. +Suspense를 지원하는 프레임워크는 일반적으로 자체 캐싱 및 무효화 메커니즘을 제공합니다. 위의 커스텀 캐시는 패턴을 이해하는 데 유용하지만, 실제로는 프레임워크의 데이터 가져오기 솔루션을 사용하는 것이 좋습니다. --- -### Preloading data on hover {/*preloading-data-on-hover*/} +### 호버 시 데이터 미리 불러오기 {/*preloading-data-on-hover*/} -You can start loading data before it's needed by calling `fetchData` during a hover event. Since `fetchData` caches the Promise, the data may already be available by the time the user clicks. If the Promise has resolved by the time `use` reads it, React renders the component immediately without showing a Suspense fallback. +호버 이벤트가 발생할 때 `fetchData`를 호출하면 데이터가 필요해지기 전에 미리 불러오기 시작할 수 있습니다. `fetchData`는 Promise를 캐시하므로 사용자가 클릭할 때쯤에는 데이터가 이미 준비되어 있을 수 있습니다. `use`가 Promise를 읽을 때 이미 리졸브되어 있다면 React는 Suspense Fallback을 표시하지 않고 컴포넌트를 즉시 렌더링합니다. ```js