Skip to content
Merged
Show file tree
Hide file tree
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
Binary file removed public/images/team/gh-rh389.jpg
Binary file not shown.
177 changes: 162 additions & 15 deletions src/content/reference/react-dom/browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,153 @@ export default function SavedDraft() {

---

### Conditionally rendering in the browser {/*conditionally-rendering-in-the-browser*/}
### Conditionally rendering on the server {/*conditionally-rendering-on-the-server*/}

Like other calls to [`use`](/reference/react/use), you can call `use(browser())` conditionally or inside a custom Hook. For example, you can wrap a Suspense-enabled data-fetching library's `useQuery` and skip server rendering when initial data is missing:
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.

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.

Click **Reload** to see the loading fallback before the user's time zone appears.

<Sandpack>

```js src/App.js
import { Suspense } from 'react';
import { useTimeZone } from './useTimeZone.js';

function TimeZone({label, defaultTimeZone}) {
const timeZone = useTimeZone(defaultTimeZone);
return <p>{label}: <strong>{timeZone}</strong></p>;
}

export default function App() {
return (
<>
<h1>Event details</h1>
<TimeZone
label="Event time zone"
defaultTimeZone="America/New_York"
/>
<Suspense fallback={<p>Loading your time zone...</p>}>
<TimeZone label="Your time zone" />
</Suspense>
</>
);
}
```

```js src/useTimeZone.js active
import { use } from 'react';
import { browser } from 'react-dom';

export function useTimeZone(defaultTimeZone) {
if (defaultTimeZone !== undefined) {
return defaultTimeZone;
}

use(browser('No default time zone was provided.'));
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}
```

```js src/Document.js hidden
import App from './App.js';

export default function Document() {
return (
<html lang="en">
<head>
<title>Event details</title>
<style>{`
h1 { font-size: 24px; margin-top: 0; }
`}</style>
</head>
<body>
<App />
</body>
</html>
);
}
```

```js src/index.js hidden
import { hydrateRoot } from 'react-dom/client';
import { renderToReadableStream } from 'react-dom/server';
import Document from './Document.js';
import { flushReadableStreamToFrame } from './demo-helpers.js';
import './styles.css';

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 />);
}

main(document.getElementById('preview'));
```

```js src/demo-helpers.js hidden
export async function flushReadableStreamToFrame(readable, frame) {
const doc = frame.contentWindow.document;
const decoder = new TextDecoder();
const reader = readable.getReader();

while (true) {
const {done, value} = await reader.read();
if (done) {
break;
}
doc.write(decoder.decode(value, {stream: true}));
}

doc.write(decoder.decode());
doc.close();
}
```

```html public/index.html hidden
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Conditional browser rendering</title>
</head>
<body>
<iframe id="preview" title="Rendered page"></iframe>
</body>
</html>
```

```css src/styles.css hidden
iframe {
width: 100%;
height: 240px;
border: 0;
}
```

```json package.json hidden
{
"dependencies": {
"react": "19.3.0-canary-eb8feb71-20260814",
"react-dom": "19.3.0-canary-eb8feb71-20260814",
"react-scripts": "latest"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
```

</Sandpack>

You can apply a similar pattern to conditionally avoid server rendering when using a Suspense-enabled data-fetching library:

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

On the server, `useBrowserQuery` calls `useQuery` only when `initialData` is available. Otherwise, the closest Suspense boundary's fallback remains in the HTML. In the browser, `use(browser())` returns `undefined`, so the query library can fetch the data or read it from its client cache.
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.

---

Expand All @@ -275,19 +419,22 @@ function SavedDraft() {
return <DraftEditor initialDraft={draft} />;
}

const { pipe } = renderToPipeableStream(
<Suspense fallback={<p>Loading saved draft...</p>}>
<SavedDraft />
</Suspense>,
{
onShellReady() {
pipe(response);
},
onBrowserBailout(error, errorInfo) {
logBrowserBailout(error, errorInfo);
}
function App() {
return (
<Suspense fallback={<p>Loading saved draft...</p>}>
<SavedDraft />
</Suspense>
);
}

const { pipe } = renderToPipeableStream(<App />, {
onShellReady() {
pipe(response);
},
onBrowserBailout(error, errorInfo) {
logBrowserBailout(error, errorInfo);
}
);
});
```

`onBrowserBailout` receives two arguments:
Expand Down
1 change: 1 addition & 0 deletions src/content/reference/react-dom/client/hydrateRoot.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ React will attach to the HTML that exists inside the `domNode`, and take over ma
* **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`.
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`.
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
* **optional** `formState`: The form state from a form submission handled by a [Server Function](/reference/rsc/server-functions). If the page was rendered on the server in response to a submission of a form that uses [`useActionState`](/reference/react/useActionState) with a `permalink`, pass the resulting form state so that `useActionState` returns the submitted state instead of the `initialState`. Must be the same value as the `formState` passed to the [server renderer.](/reference/react-dom/server/renderToPipeableStream#parameters) This is typically passed through by your framework.


#### Returns {/*returns*/}
Expand Down
8 changes: 4 additions & 4 deletions src/content/reference/react-dom/server/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ title: Sunucu React DOM API'leri

Bu metodlar sadece tarayıcılar, Deno ve bazı modern edge runtime'ları gibi [Web Stream'leri](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) içeren ortamlarda kullanılabilir:

* [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream), bir React ağacını [Readable Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) olarak render eder.
* [`resume`](/reference/react-dom/server/renderToPipeableStream), [`prerender`](/reference/react-dom/static/prerender) işlemini bir [Readable Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) olarak devam ettirir.
* [`renderToReadableStream`](/reference/react-dom/server/renderToReadableStream), bir React tree’sini [Readable Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) olarak render eder.
* [`resume`](/reference/react-dom/server/resume), [`prerender`](/reference/react-dom/static/prerender) işlemini bir [Readable Web Stream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) olarak resume eder.


<Note>
Expand All @@ -29,8 +29,8 @@ Node.js ayrıca uyumluluk için bu yöntemleri de içerir, ancak performansın d

Bu yöntemler yalnızca [Node.js Stream'leri](https://nodejs.org/api/stream.html) olan ortamlarda kullanılabilir:

* [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream), bir React ağacını pipe edilebilir bir [Node.js Stream](https://nodejs.org/api/stream.html) olarak render eder.
* [`resumeToPipeableStream`](/reference/react-dom/server/renderToPipeableStream), [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) işlemini pipe edilebilir bir [Node.js Stream](https://nodejs.org/api/stream.html) olarak devam ettirir.
* [`renderToPipeableStream`](/reference/react-dom/server/renderToPipeableStream), bir React tree’sini pipeable bir [Node.js Stream](https://nodejs.org/api/stream.html) olarak render eder.
* [`resumeToPipeableStream`](/reference/react-dom/server/resumeToPipeableStream), [`prerenderToNodeStream`](/reference/react-dom/static/prerenderToNodeStream) işlemini pipeable bir [Node.js Stream](https://nodejs.org/api/stream.html) olarak resume eder.

---

Expand Down
14 changes: 9 additions & 5 deletions src/content/reference/react-dom/server/renderToPipeableStream.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,17 @@ const { pipe } = renderToPipeableStream(<App />, {
* **optional** `options`: Streaming options içeren bir object.
* **optional** `bootstrapScriptContent`: Belirtilirse, bu string inline bir `<script>` tag’i içine yerleştirilir.
* **optional** `bootstrapScripts`: Sayfada emit edilecek `<script>` tag’leri için string URL’lerden oluşan bir array. [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) çağıran `<script>`’i dahil etmek için bunu kullanın. Client tarafında React’i hiç çalıştırmak istemiyorsanız bunu atlayın.
* **optional** `bootstrapModules`: `bootstrapScripts` gibidir, ancak bunun yerine [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) emit eder.
* **optional** `bootstrapModules`: `bootstrapScripts` ile benzerdir, ancak bunun yerine [`<script type="module">`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) emit eder.
* **optional** `formState`: Bir [Server Function](/reference/rsc/server-functions) tarafından işlenen form submission’ından elde edilen form state. Sayfa, `permalink` ile [`useActionState`](/reference/react/useActionState) kullanan bir form’un submit edilmesine yanıt olarak render ediliyorsa, React’in hydration için HTML’e embed etmesi amacıyla elde edilen form state’i geçirin. Aynı value, client tarafında [`hydrateRoot`](/reference/react-dom/client/hydrateRoot#parameters)’a da geçirilmelidir. Bu işlem genellikle framework’ünüz tarafından gerçekleştirilir.
* **optional** `identifierPrefix`: React’in [`useId`](/reference/react/useId) tarafından oluşturulan ID’ler için kullandığı string prefix. Aynı sayfada birden fazla root kullanırken conflict’leri önlemek için kullanışlıdır. [`hydrateRoot`](/reference/react-dom/client/hydrateRoot#parameters)’a geçirilen prefix ile aynı olmalıdır.
* **optional** `importMap`: `imports` ve `scopes` property’lerini içeren bir [import map](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap) object’i. React, bunu herhangi bir module script’inden önce inline bir `<script type="importmap">` tag’i olarak emit eder. Böylece `<script type="module">` tag’leri (örneğin `bootstrapModules` üzerinden oluşturulanlar) bare module specifier’ları kullanabilir. <CanaryBadge /> `nonce` ayarlandığında, import map script’ine de uygulanır.
* **optional** `maxHeadersLength`: `onHeaders`’a geçirilen header content’inin UTF-16 code unit cinsinden ölçülen maksimum toplam uzunluğu. Default değeri 2000’dir. Bu limite ulaşıldığında React, header’lara resource hint eklemeyi durdurur.
* **optional** `namespaceURI`: Stream için root [namespace URI](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#important_namespace_uris)’sini içeren bir string. Default olarak normal HTML’dir. SVG için `'http://www.w3.org/2000/svg'`, MathML için `'http://www.w3.org/1998/Math/MathML'` geçirin.
* **optional** `nonce`: [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) için script’lere izin veren bir [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string’i.
* **optional** `onAllReady`: Hem [shell](#specifying-what-goes-into-the-shell) hem de tüm ek [content](#streaming-more-content-as-it-loads) dahil olmak üzere tüm rendering tamamlandığında tetiklenen bir callback. Bunu `onShellReady` yerine [crawler’lar ve static generation](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) için kullanabilirsiniz. Burada streaming’i başlatırsanız progressive loading elde etmezsiniz. Stream final HTML’i içerir.
* <CanaryBadge /> **optional** `onBrowserBailout`: React’in [`browser()`](/reference/react-dom/browser)’dan, browser’ın replace etmesi için bir Suspense fallback bırakarak recover olduğunda çağırdığı bir callback. Browser-only render’ı açıklayan bir `Error` ve `componentStack` içeren bir `errorInfo` object’i alır. `browser`’a bir reason geçirildiyse, buna `error.cause` üzerinden erişilebilir. Default olarak React hiçbir şey yapmaz. [Browser-only rendering’in nasıl report edileceğine bakın.](/reference/react-dom/browser#reporting-browser-only-rendering-on-the-server)
* **optional** `onError`: [Recoverable](#recovering-from-errors-outside-the-shell) olsun ya da [olmasın](#recovering-from-errors-inside-the-shell), server error olduğunda tetiklenen bir callback. Default olarak yalnızca `console.error` çağırır. [Crash report’ları loglamak](#logging-crashes-on-the-server) için override ederseniz, yine de `console.error` çağırdığınızdan emin olun. Shell emit edilmeden önce [status code’u ayarlamak](#setting-the-status-code) için de kullanabilirsiniz.
* **optional** `nonce`: [`script-src` Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) kapsamında script’lere izin veren bir [`nonce`](http://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#nonce) string’i. Script ve style’lar için farklı nonce’lar kullanmak istiyorsanız, bunun yerine `script` ve `style` property’lerini içeren bir object geçirin.
* **optional** `onAllReady`: Hem [shell](#specifying-what-goes-into-the-shell) hem de tüm ek [content](#streaming-more-content-as-it-loads) dahil olmak üzere tüm rendering tamamlandığında tetiklenen bir callback. Bunu `onShellReady` yerine [crawler’lar ve static generation](#waiting-for-all-content-to-load-for-crawlers-and-static-generation) için kullanabilirsiniz. Streaming’i burada başlatırsanız progressive loading elde edemezsiniz. Stream, final HTML’i içerir.
* <CanaryBadge /> **optional** `onBrowserBailout`: React’in [`browser()`](/reference/react-dom/browser) nedeniyle browser’ın replace etmesi için bir Suspense fallback bırakarak recover olduğunda çağırdığı bir callback. Browser-only render’ı açıklayan bir `Error` ve `componentStack` içeren bir `errorInfo` object’i alır. `browser`’a bir reason geçirildiyse, buna `error.cause` üzerinden erişilebilir. Default olarak React hiçbir şey yapmaz. [Browser-only rendering’in nasıl report edileceğine bakın.](/reference/react-dom/browser#reporting-browser-only-rendering-on-the-server)
* **optional** `onError`: [Recoverable](#recovering-from-errors-outside-the-shell) olsun ya da [olmasın](#recovering-from-errors-inside-the-shell), server error oluştuğunda tetiklenen bir callback. Default olarak yalnızca `console.error` çağırır. [Crash report’ları loglamak](#logging-crashes-on-the-server) için override ederseniz, yine de `console.error` çağırdığınızdan emin olun. Shell emit edilmeden önce [status code’u ayarlamak](#setting-the-status-code) için de kullanabilirsiniz.
* **optional** `onHeaders`: React, document için preconnect’ler ve stylesheet, font veya high-priority image preload’ları gibi resource hint’leri belirlediğinde tetiklenen bir callback. İlgili [`Link` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/link) value’sunu içeren bir `Link` property’sine sahip object alır. Böylece bu value’yu HTTP response header olarak veya [103 Early Hints](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103) response olarak gönderebilirsiniz. Gönderilecek resource hint olmasa bile React bu callback’i çağırır. Header content’i `maxHeadersLength` ile sınırlandırılır.
* **optional** `onShellReady`: [Initial shell](#specifying-what-goes-into-the-shell) render edildikten hemen sonra tetiklenen bir callback. Burada [status code’u ayarlayabilir](#setting-the-status-code) ve streaming’i başlatmak için `pipe` çağırabilirsiniz. React, shell’den sonra ek [content’i stream eder](#streaming-more-content-as-it-loads) ve HTML loading fallback’lerini content ile değiştiren inline `<script>` tag’lerini de beraberinde gönderir.
* **optional** `onShellError`: Initial shell render edilirken bir error oluşursa tetiklenen bir callback. Error’ı argüman olarak alır. Stream’den henüz hiç byte emit edilmemiştir ve ne `onShellReady` ne de `onAllReady` çağrılır; bu yüzden [fallback HTML shell output edebilirsiniz](#recovering-from-errors-inside-the-shell).
* **optional** `progressiveChunkSize`: Bir chunk içindeki byte sayısı. [Default heuristic hakkında daha fazla okuyun.](https://github.com/react/react/blob/14c2be8dac2d5482fda8a0906a31d239df8551fc/packages/react-server/src/ReactFizzServer.js#L210-L225)
Expand Down
Loading
Loading