Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 38 additions & 38 deletions src/content/reference/react-dom/browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: browser

<Intro>

`browser` lets you mark a component as browser-only during server rendering.
`browser`를 사용하면 서버 렌더링 동안 컴포넌트를 브라우저에서만 렌더링하도록 표시할 수 있습니다.

```js
use(browser(reason?))
Expand All @@ -16,11 +16,11 @@ use(browser(reason?))

---

## Reference {/*reference*/}
## 레퍼런스 {/*reference*/}

### `browser(reason?)` {/*browser*/}

Call `browser` inside [`use`](/reference/react/use) to mark a component as browser-only during server rendering:
[`use`](/reference/react/use) 내부에서 `browser`를 호출하여 서버 렌더링 동안 컴포넌트를 브라우저 전용으로 표시합니다.

```js
import { use } from 'react';
Expand All @@ -32,35 +32,35 @@ function BrowserOnly() {
}
```

During server rendering, `use(browser())` stops rendering the component and leaves the closest [`<Suspense>`](/reference/react/Suspense) boundary's fallback in its place. In the browser, `use(browser())` returns `undefined`, so the component renders normally.
서버 렌더링 동안 `use(browser())`는 컴포넌트의 렌더링을 멈추고 그 자리에 가장 가까운 [`<Suspense>`](/reference/react/Suspense) 경계의 폴백을 남깁니다. 브라우저에서는 `use(browser())`가 `undefined`를 반환하므로 컴포넌트가 정상적으로 렌더링됩니다.

[See more examples below.](#usage)
[아래에서 더 많은 예시를 확인하세요.](#usage)

#### Parameters {/*parameters*/}
#### 매개변수 {/*parameters*/}

* **optional** `reason`: A string or function that explains why the content needs to render in the browser. The string or the function's return value becomes the `cause` of the `Error` passed to [`onBrowserBailout`](#reporting-browser-only-rendering-on-the-server). React calls a reason function each time a server renderer encounters the value returned by `browser`, but does not call it in the browser. If creating the reason is expensive, pass a function such as `() => new Error(...)`.
* `reason`**(선택사항)**: 콘텐츠가 왜 브라우저에서 렌더링되어야 하는지 설명하는 문자열 또는 함수입니다. 문자열 또는 함수의 반환값은 [`onBrowserBailout`](#reporting-browser-only-rendering-on-the-server)에 전달되는 `Error`의 `cause`가 됩니다. React는 서버 렌더러가 `browser`의 반환값을 마주칠 때마다 `reason` 함수를 호출하지만, 브라우저에서는 호출하지 않습니다. `reason`을 만드는 비용이 크다면 `() => new Error(...)`와 같은 함수를 전달하세요.

#### Returns {/*returns*/}
#### 반환값 {/*returns*/}

`browser` returns an opaque value that you can pass to `use` in a component or use as the reason when [aborting a server render](#aborting-pending-server-rendering-for-the-browser). In the browser, passing this value to `use` returns `undefined`.
`browser`는 불투명한 값을 반환합니다. 이 값은 컴포넌트에서 `use`에 전달하거나 [서버 렌더링을 중단할 때](#aborting-pending-server-rendering-for-the-browser) `reason`으로 사용할 수 있습니다. 브라우저에서 이 값을 `use`에 전달하면 `undefined`가 반환됩니다.

#### Caveats {/*caveats*/}
#### 주의 사항 {/*caveats*/}

* `use(browser())` must be inside a `<Suspense>` boundary during server rendering. Without one, the server render fails.
* `use(browser())` must be called from a [Client Component](/reference/rsc/use-client), not a [Server Component](/reference/rsc/server-components).
* Calling `browser()` by itself has no effect. To mark a component as browser-only, pass the value returned by `browser` to `use`. Do not throw it.
* `use(browser())`는 서버 렌더링 동안 `<Suspense>` 경계 내부에 있어야 합니다. 경계가 없으면 서버 렌더링이 실패합니다.
* `use(browser())`는 [서버 컴포넌트](/reference/rsc/server-components)가 아니라 [클라이언트 컴포넌트](/reference/rsc/use-client)에서 호출해야 합니다.
* `browser()`를 단독으로 호출하는 것은 아무 효과가 없습니다. 컴포넌트를 브라우저 전용으로 표시하려면 `browser`가 반환한 값을 `use`에 전달하세요. 이 값을 throw하지 마세요.

---

## Usage {/*usage*/}
## 사용법 {/*usage*/}

### Rendering content only in the browser {/*rendering-content-only-in-the-browser*/}
### 브라우저에서만 콘텐츠 렌더링하기 {/*rendering-content-only-in-the-browser*/}

Call `browser` inside `use` in a component that should only render in the browser:
브라우저에서만 렌더링되어야 하는 컴포넌트의 `use` 안에서 `browser`를 호출하세요.

You can use this instead of checking `typeof window`, waiting for an [`Effect`](/reference/react/useEffect) to set mounted state, or using a framework option to disable server rendering.
`typeof window`를 확인하거나, 마운트 상태를 설정하는 [`Effect`](/reference/react/useEffect)를 기다리거나, 서버 렌더링을 비활성화하는 프레임워크 옵션을 사용하는 대신 이 방법을 사용할 수 있습니다.

Click **Reload** to see the loading fallback in the initial HTML. After hydration, React displays the draft loaded from `localStorage`.
초기 HTML에서 로딩 폴백을 보려면 **Reload**를 클릭하세요. 하이드레이션 이후 React는 `localStorage`에서 불러온 초안을 표시합니다.

<Sandpack>

Expand Down Expand Up @@ -138,7 +138,7 @@ async function main(frame) {
const stream = await renderToReadableStream(<Document />);
await flushReadableStreamToFrame(stream, frame);

// Wait so both the fallback and hydrated content are visible.
// 폴백과 하이드레이션된 콘텐츠가 모두 보이도록 대기합니다.
await new Promise(resolve => setTimeout(resolve, 1200));
hydrateRoot(frame.contentDocument, <Document />);
}
Expand Down Expand Up @@ -206,7 +206,7 @@ iframe {

<Note>

`use(browser())` must be called from a Client Component. If your framework uses Server Components by default, add the [`'use client'`](/reference/rsc/use-client) directive to that file or move the call to a child Client Component:
`use(browser())`는 클라이언트 컴포넌트에서 호출해야 합니다. 사용 중인 프레임워크가 기본적으로 서버 컴포넌트를 사용한다면 해당 파일에 [`'use client'`](/reference/rsc/use-client) 지시어를 추가하거나 호출을 자식 클라이언트 컴포넌트로 옮기세요.

```js {1}
'use client';
Expand All @@ -225,13 +225,13 @@ export default function SavedDraft() {

---

### Conditionally rendering on the server {/*conditionally-rendering-on-the-server*/}
### 서버에서 조건부로 렌더링하기 {/*conditionally-rendering-on-the-server*/}

Like other calls to [`use`](/reference/react/use), `use(browser())` can be called inside a conditional statement or after an early return. This lets a Component or custom Hook opt out of server rendering based on a condition, such as the value of a prop.
다른 [`use`](/reference/react/use) 호출과 마찬가지로 `use(browser())`는 조건문 내부나 early return 이후에도 호출할 수 있습니다. 이를 통해 컴포넌트나 커스텀 Hook에서 prop 값과 같은 조건에 따라 서버 렌더링을 건너뛸 수 있습니다.

For example, this `useTimeZone` Hook accepts an optional default value. When provided, React renders the default value in the initial HTML and in the browser. Without a default value, the Component suspends during server rendering and shows the device's local time zone in the browser.
예를 들어 `useTimeZone` Hook은 기본값을 선택적으로 받습니다. 기본값이 제공되면 React는 초기 HTML과 브라우저 모두에서 기본값을 렌더링합니다. 기본값이 없으면 컴포넌트는 서버 렌더링 동안 일시 중단되고, 브라우저에서 기기의 로컬 시간대를 표시합니다.

Click **Reload** to see the loading fallback before the user's time zone appears.
사용자의 시간대가 나타나기 전에 표시되는 로딩 폴백을 보려면 **Reload**를 클릭하세요.

<Sandpack>

Expand Down Expand Up @@ -305,7 +305,7 @@ async function main(frame) {
const stream = await renderToReadableStream(<Document />);
await flushReadableStreamToFrame(stream, frame);

// Wait so both the fallback and hydrated content are visible.
// 폴백과 하이드레이션된 콘텐츠가 모두 보이도록 대기합니다.
await new Promise(resolve => setTimeout(resolve, 1200));
hydrateRoot(frame.contentDocument, <Document />);
}
Expand Down Expand Up @@ -371,7 +371,7 @@ iframe {

</Sandpack>

You can apply a similar pattern to conditionally avoid server rendering when using a Suspense-enabled data-fetching library:
Suspense를 지원하는 데이터 페칭 라이브러리를 사용할 때도 비슷한 패턴을 적용해 조건부로 서버 렌더링을 피할 수 있습니다.

```js {3}
function useBrowserQuery(query, options) {
Expand All @@ -391,13 +391,13 @@ function ProductDetails({ productId, initialData }) {
}
```

With `initialData`, React renders the Component to HTML on the server. Without it, React leaves the closest [`<Suspense>`](/reference/react/Suspense) boundary's fallback in the HTML. In the browser, `useQuery` can fetch the data or read it from its client cache as usual.
`initialData`가 있으면 React는 서버에서 컴포넌트를 HTML로 렌더링합니다. 없으면 React는 가장 가까운 [`<Suspense>`](/reference/react/Suspense) 경계의 폴백을 HTML에 남깁니다. 브라우저에서는 `useQuery`가 평소처럼 데이터를 페치하거나 클라이언트 캐시에서 읽어올 수 있습니다.

---

### Reporting browser-only rendering on the server {/*reporting-browser-only-rendering-on-the-server*/}
### 서버에서 브라우저 전용 렌더링 보고하기 {/*reporting-browser-only-rendering-on-the-server*/}

Pass an `onBrowserBailout` callback to the server renderer to report browser-only rendering. When React leaves a Suspense fallback for the browser, it does not call the server renderer's `onError` callback or [`hydrateRoot`'s `onRecoverableError`](/reference/react-dom/client/hydrateRoot#error-logging-in-production) callback. This example also passes a reason, which is available as the reported error's `cause`:
브라우저 전용 렌더링을 보고하려면 서버 렌더러에 `onBrowserBailout` 콜백을 전달하세요. React가 브라우저를 위해 Suspense 폴백을 남길 때는 서버 렌더러의 `onError` 콜백이나 [`hydrateRoot`의 `onRecoverableError`](/reference/react-dom/client/hydrateRoot#error-logging-in-production) 콜백을 호출하지 않습니다. 이 예시에서는 `reason`도 함께 전달하며, 보고된 에러의 `cause`로 확인할 수 있습니다.

```js
import { Suspense, use, useState } from 'react';
Expand Down Expand Up @@ -428,20 +428,20 @@ const { pipe } = renderToPipeableStream(<App />, {
});
```

`onBrowserBailout` receives two arguments:
`onBrowserBailout`은 두 개의 인수를 받습니다.

1. An `Error` describing the browser-only render. If you passed a reason to `browser`, it is available as the error's `cause`.
2. An `errorInfo` object with a `componentStack` showing where browser-only rendering occurred.
1. 브라우저 전용 렌더링을 설명하는 `Error`. `browser`에 `reason`을 전달했다면 에러의 `cause`로 확인할 수 있습니다.
2. 브라우저 전용 렌더링이 발생한 위치를 보여주는 `componentStack`을 담은 `errorInfo` 객체.

The reason function can return any value. Return a new `Error` to give the cause its own stack without creating the `Error` in the browser. React does not serialize the reason into the HTML.
`reason` 함수는 어떤 값이든 반환할 수 있습니다. 새로운 `Error`를 반환하면 브라우저에서 `Error`를 생성하지 않고도 `cause`가 자체 스택을 갖게 할 수 있습니다. React는 `reason`을 HTML로 직렬화하지 않습니다.

If there is no Suspense boundary to provide a fallback, the server render fails. React reports the failure through the renderer's usual error callbacks instead of `onBrowserBailout`.
폴백을 제공할 Suspense 경계가 없으면 서버 렌더링이 실패합니다. 이때 React는 `onBrowserBailout` 대신 렌더러의 일반적인 에러 콜백을 통해 실패를 보고합니다.

---

### Aborting pending server rendering for the browser {/*aborting-pending-server-rendering-for-the-browser*/}
### 브라우저를 위해 대기 중인 서버 렌더링 중단하기 {/*aborting-pending-server-rendering-for-the-browser*/}

If you call a server rendering API directly, you can stop waiting for pending content and let the browser finish rendering it. Pass the value returned by `browser` as the reason when aborting the server render. React then leaves pending Suspense boundaries in their fallback state and renders their content in the browser:
서버 렌더링 API를 직접 호출한다면 대기 중인 콘텐츠를 더 기다리지 않고 브라우저가 렌더링을 마무리하도록 둘 수 있습니다. 서버 렌더링을 중단할 때 `browser`가 반환한 값을 `reason`으로 전달하세요. 그러면 React는 대기 중인 Suspense 경계를 폴백 상태로 남겨두고, 브라우저에서 해당 콘텐츠를 렌더링합니다.

```js {1,8}
import { browser } from 'react-dom';
Expand All @@ -457,6 +457,6 @@ const { pipe, abort } = renderToPipeableStream(<App />, {
});
```

A `browser` abort reason does not trigger the server renderer's `onError` callback or `hydrateRoot`'s `onRecoverableError` callback. Instead, the server renderer reports each recovered Suspense boundary to `onBrowserBailout`.
`browser()`를 `reason`으로 전달해 중단하면 React는 서버 렌더러의 `onError` 콜백이나 `hydrateRoot`의 `onRecoverableError` 콜백을 호출하지 않습니다. 대신 서버 렌더러는 복구된 Suspense 경계마다 `onBrowserBailout`을 호출합니다.

For server rendering APIs that accept an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal), pass `browser()` as the reason to [`AbortController.abort`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort).
[`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)을 받는 서버 렌더링 API에서는 [`AbortController.abort`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort)에 `browser()`를 `reason`으로 전달하세요.
Loading